0
List<Map<String, Object>> list =new ArrayList();
Map<String, Object> map1 =new HashMap();
List<String> values =new ArrayList();
values.add("TEST")
values.add("TEST1")
map1.put("level",values);
Map<String, Object> map2 =new HashMap();
List<String> values2 =new ArrayList();
values2.add("TEST2")
values2.add("TEST3")
map2.put("level",values2);
list.add(map1);
list.add(map2);

I want the result like a list of flat string values

List<String> values =["TEST","TEST1","TES2","TEST3"]
HoRn
  • 1,458
  • 5
  • 20
  • 25
  • 1
    What have you tried? There are **no** streams in your code, which by the way would fail to compile. Please share your attempt and specify the issue you've encountered? Every question of SO is expected to demonstrate an **effort**. Please get familiar with the guide-lines on how to ask questions [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Alexander Ivanchenko Oct 17 '22 at 09:50
  • `list.stream().flatMap(map -> map.values().stream().flatMap(List::stream)).toList()` –  Oct 17 '22 at 09:53
  • 1
    Possible duplicate https://stackoverflow.com/questions/22382453/java-8-streams-flatmap-method-example – Alexander Ivanchenko Oct 17 '22 at 09:56

2 Answers2

0
List<Object> collect = list
                .stream()
                .flatMap(x -> x.entrySet().stream())
                .map(Map.Entry::getValue)
                .flatMap(x -> {
                            if (x instanceof Collection<?>) {
                                return ((Collection<?>) x).stream();
                            } else {
                                return Stream.of(x);
                            }
                        }
                )
                .collect(Collectors.toList());
0

Change the Maps to have typed values, eg

List<Map<String, List<String>>> list = new ArrayList<>();
Map<String, List<String>> map1 = new HashMap<>();

Then use flatMap() twice to double flatten the collections:

List<String> allValues = list.stream() // a stream of Maps
  .map(Map::values) // a stream of Collection<List<String>>
  .flatMap(Collection::stream) // a stream of List<String>
  .flatMap(List::stream) // a stream of String
  .collect(toList());

See live demo.


If you leave the values of the Maps as Object, you need the cast them:

List<String> allValues = list.stream() // a stream of Maps
  .map(Map::values) // a stream of Collection<Object>
  .map(o -> (Collection<List<String>>)o)
  .flatMap(Collection::stream) // a stream of List<Object>
  .map(o -> (List<String>)o)
  .flatMap(List::stream) // a stream of String
  .collect(toList());

Which is uglier, less safe and unnecessary with the correct typing.

samabcde
  • 6,988
  • 2
  • 25
  • 41
Bohemian
  • 412,405
  • 93
  • 575
  • 722