Using Java 8 streamingBy grouping in map list list?

From the following input

[
   [{group=a, value=cat}, {group=b, value=dog}],
   [{group=a, value=cow}, {group=b, value=bat}]
]

how to get the following output

{
   a=[{value=cat}, {value=cow}],
   b=[{value=dog}, {value=bat}]
}

using Java 8 threads?

I have the following standard solution

Map<String, String > map1 = new LinkedHashMap<>();
map1.put("group", "a");
map1.put("value", "cat");
Map<String, String > map2 = new LinkedHashMap<>();
map2.put("group", "b");
map2.put("value", "dog");
Map<String, String > map3 = new LinkedHashMap<>();
map3.put("group", "a");
map3.put("value", "cow");
Map<String, String > map4 = new LinkedHashMap<>();
map4.put("group", "b");
map4.put("value", "bat");

List<Map<String, String>> list1 = Arrays.asList(map1, map2);
List<Map<String, String>> list2 = Arrays.asList(map3, map4);

List<List<Map<String, String>>> input = Arrays.asList(list1, list2);

Map<String, List<Map<String, String>>> output = new LinkedHashMap<>();
for (List<Map<String, String>> list : input) {
   for (Map<String, String> map : list) {
       String group = map.get("group");
       if (!output.containsKey(group)) {
           output.put(group, new ArrayList<>());
       }
       List<Map<String, String>> values = output.get(group);
       values.add(map);
   }
}

I saw that there was a method Collectors.groupingBy, but I could not figure out how to use it.

Map<String, List<Map<String, String>>> output = input.stream()
  .<am I missing out some steps here?>
  .collect(Collectors.groupingBy(<what goes here?>))
+4
source share
1 answer

To generate the same output, you must flatten the list of lists into a single list with flatMapbefore grouping:

output = input.stream().flatMap(List::stream)
              .collect(Collectors.groupingBy(map -> map.get("group")));

This code generates the same result as the required code you posted:

{
 a=[{group=a, value=cat}, {group=a, value=cow}], 
 b=[{group=b, value=dog}, {group=b, value=bat}]
}

, . , :

output = input.stream()
              .flatMap(List::stream)
              .collect(Collectors.groupingBy(map -> map.get("group"),
                 Collectors.mapping(
                     map -> Collections.singletonMap("value", map.get("value")), 
                      Collectors.toList())));

{
  a=[{value=cat}, {value=cow}], 
  b=[{value=dog}, {value=bat}]
}
+7

Source: https://habr.com/ru/post/1625500/


All Articles