Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding duplicated objects by two properties

Tags:

java

java-8

Considering that I have a list of Person objects like this :

Class Person {
  String fullName;
  String occupation;
  String hobby;
  int salary;
}

Using java8 streams, how can I get list of duplicated objects only by fullName and occupation property?

like image 833
kkot Avatar asked Dec 02 '22 10:12

kkot


2 Answers

By using java-8 Stream() and Collectors.groupingBy() on firstname and occupation

List<Person> duplicates = list.stream()
    .collect(Collectors.groupingBy(p -> p.getFullName() + "-" + p.getOccupation(), Collectors.toList()))
    .values()
    .stream()
    .filter(i -> i.size() > 1)
    .flatMap(j -> j.stream())
    .collect(Collectors.toList());
like image 118
Deadpool Avatar answered Jan 04 '23 04:01

Deadpool


I need to find if they were any duplicates in fullName - occupation pair, which has to be unique

Based on this comment it seems that you don't really care about which Person objects were duplicated, just that there were any.

In that case you can use a stateful anyMatch:

Collection<Person> input = new ArrayList<>();

Set<List<String>> seen = new HashSet<>();
boolean hasDupes = input.stream()
                        .anyMatch(p -> !seen.add(List.of(p.fullName, p.occupation)));

You can use a List as a 'key' for a set which contains the fullName + occupation combinations that you've already seen. If this combination is seen again you immediately return true, otherwise you finish iterating the elements and return false.

like image 41
Jorn Vernee Avatar answered Jan 04 '23 05:01

Jorn Vernee