I have list of Object . I want to compare elements of the list and perform operation if the are equal on a condition.
class A{ String abc; int pqr; }
I have List items with me
"items": [ { "pqr": 2, "abc": 1994 }, { "pqr": 2, "abc": 1994 }, { "pqr": 1, "abc": 64 } ]
Now i want my output list as
"items": [ { "pqr": 4, "abc": 1994 }, { "pqr": 1, "abc": 64 } ]
i/e comparing th elements on the basis of abc and if its is same add its pqr value and remove the duplicate.
How can i do this using stream or efficiently?
As mentioned by Ralf you can use groupingBy
to get a Map
with abc
as key and the sum of pqr
as value:
Map<String, Integer> groupBy = list.stream()
.collect(Collectors.groupingBy(Container::getAbc, Collectors.summingInt(Container::getPqr)));
System.out.println(groupBy);
produces {1994=4, 64=1}
.
If you need to convert this to a List
you have to iterate over this map
:
List<Container> list = groupBy.entrySet()
.stream()
.map(e -> new Container(e.getKey(), e.getValue()))
.collect(Collectors.toList());
System.out.println(list);
produces (with overwritten toString
) [A{abc=1994, pqr=4}, A{abc=64, pqr=1}]