After a stream().filter().map()
on a List I have a data structure of type List<List<Object>>
that looks like this:
[["1","a",20],
["1","b",10],
["2","a",10],
["2","b",30]]
What I want is to group by the value of the first element of the inner list, leave the middle element out and finally sum the last elements for each "group".
[["1", 30],
["2", 40]]
Sorry if this is obvious for some of you, but I have yet to find any example of how to achieve this. I assumed it could be done by Stream.reduce(U identity, BiFunction accumulator, BinaryOperator combiner) but so far I haven't succeeded. If someone could provide some example code for this, I believe it would be appreciated by many others too.
The following code may be of help:
List<List<Object>> originalList = Arrays.asList(
Arrays.asList("1", "a", 20),
Arrays.asList("1", "b", 10),
Arrays.asList("2", "a", 10),
Arrays.asList("2", "b", 30)
);
final Map<Object, Integer> collectedMap =
originalList.stream()
.collect(Collectors.groupingBy(
e -> e.get(0),
Collectors.summingInt(e -> (Integer) e.get(2))));
System.out.println(collectedMap);
The output is:
{1=30, 2=40}
Basically, what the code does is to group
by the first value in the sublist (get(0)
). Then it sums the integers by the use of summingInt
. However, it groups the entire thing in a Map
- if some other collection is required the stream must be slightly changed.
E.g. to collect the whole thing as a List
:
final List<List<Object>> collectedList =
collectedMap.entrySet()
.stream()
.map(e -> Arrays.asList(e.getKey(), e.getValue()))
.collect(Collectors.toList());
System.out.println(collectedList);
Then, the output will be:
[[1, 30], [2, 40]]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments