Assume we have a person class with fields:
Class Person {
private String name;
private Integer id (this one is unique);
}
And then we have a List<Person> people
such that:
['Jerry', 993]
['Tom', 3]
['Neal', 443]
['Jerry', 112]
['Shannon', 259]
['Shannon', 533]
How can I make a new List<Person> uniqueNames
such that it filters for unique names only AND keeps the highest ID of that name.
So the end list would look like:
['Jerry', 993]
['Tom', 3]
['Neal', 443]
['Shannon', 533]
Collectors.groupingBy
+Collectors.maxBy
should do the trick to build the map of persons grouped by name and then selecting the max value:Output:
Update
It may be better to collect the grouped items in a list which should be converted then in some wrapper class providing information about the
maxById
person and the list of deduped persons:Then the persons should be collected like this:
Output:
Update 2
Getting list of duplicated persons:
Output:
where
removeMax
may be implemented like this:Or, providing that
hashCode
andequals
are implemented properly in classPerson
, the difference between the two lists may be calculated usingremoveAll
: