If you are using Java 8 you can make it using Stream API:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.reducing;
@Data
@NoArgsConstructor
@AllArgsConstructor
class Person {
private String name = "";
private Double salary = 0.0;
}
public class PersonTest {
@Test
public void test() {
List<Person> persons = Arrays.asList(
new Person("John", 2.0),
new Person("Mary", 2.4),
new Person("John", 4.0));
System.out.println(persons);
Collection<Person> filteredPersons = persons.stream()
.collect(groupingBy(Person::getName, reducing(new Person(), (p1, p2) -> new Person(p2.getName(), p1.getSalary() + p2.getSalary()))))
.values();
System.out.println(filteredPersons);
}
}
Output:
[Person(name=John, salary=2.0), Person(name=Mary, salary=2.4), Person(name=John, salary=4.0)]
[Person(name=John, salary=6.0), Person(name=Mary, salary=2.4)]
ifyou compare the name of a person with the name of the same person so it should always betrue. The same with the salary.