'Merge Person objects with similar attributes into a single Map Entry
Person.java
class Person{
String name;
Integer age;
Integer salary;
//...getter..setter
}
List of Person objects:
List<Person> tempList = new ArrayList<>(List.of(new Person("John",33,10000), new Person("Peter",21,2000), new Person("John",18,5000), new Person("Peter",31,6000)));
Using java streams, how do I tell my program to 'Find all person with same name and perform SUM operations on their Ages and on their Salaries'
So desired outcome for this would be something like:
"John", 51, 1500
"Peter", 52, 8000
What I've tried:
Map<String,Integer> NameAndSalary= tempList.stream().collect(Collectors.groupingBy(Person::getName,Collectors.summingInt(Person::getSalary) ));
Map<String,Integer> NameAndAge= tempList.stream().collect(Collectors.groupingBy(Person::getName,Collectors.summingInt(Person::getAge) ));
This is good but this produce separate results like:
"John", 51
and
"John", 1500
Is there a shortcut to make it:
"John", 51, 1500
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
