How to find duplicates in an ArrayList<Object>?

Viewed 27618

This is a pretty common question, but I could not find this part:

Say I have this array list:

List<MyDataClass> arrayList = new List<MyDataClass>;

MyDataClass{
   String name;
   String age;
}

Now, I need to find duplicates on the basis of age in MyDataClass and remove them. How is it possible using something like HashSet as described here?

I guess, we will need to overwrite equals in MyDataClass?

  1. But, what if I do not have the luxury of doing that?
  2. And How does HashSet actually internally find and does not add duplicates? I saw it's implementation here in OpenJDK but couldn't understand.
4 Answers

Suppose that you have a class named Person that has two property: id , firstName. write this mehod in its class:

String uniqueAttributes() {
  return id + firstName;
}

The getDuplicates() method is now should be such as:

public static List<Person> getDuplicates(final List<Person> personList) {
  return getDuplicatesMap(personList).values().stream()
      .filter(duplicates -> duplicates.size() > 1)
      .flatMap(Collection::stream)
      .collect(Collectors.toList());
}

private static Map<String, List<Person>> getDuplicatesMap(List<Person> personList) {
  return personList.stream().collect(groupingBy(Person::uniqueAttributes));
}
Related