Java Collection How to - Find duplicate entries in Collection








Question

We would like to know how to find duplicate entries in Collection.

Answer

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/*  w  w  w.  j  a v  a 2  s.co m*/
public class Main {
  public static void main(String[] args) throws java.lang.Exception {
    List<Person> people = new ArrayList<Person>();
    people.add(new Person("J", "S"));
    people.add(new Person("J", "S"));
    people.add(new Person("J", "F"));
    people.add(new Person("J", "W"));
    people.add(new Person("J", "B"));
    Set<Object> seen = new HashSet<Object>();
    for (Person p : people) {

      Wrap wrap = new Wrap(p);
      if (seen.add(wrap)) {
        System.out.println(p + " is new");
      } else {
        System.out.println(p + " is a duplicate");
      }
    }
  }
}
class Wrap {
  Person thisPerson;
  public Wrap(Person p){
    thisPerson = p;
  }
  public int hashCode() {
    return thisPerson.getFirst().hashCode();
  }

  public boolean equals(Object o) {
    Wrap other = (Wrap) o;
    return other.wrapped().getFirst().equals(thisPerson.getFirst());
  }

  public Person wrapped() {
    return thisPerson;
  }
}
class Person {
  private String first;
  private String last;

  public String getFirst() {
    return first;
  }

  public String getLast() {
    return last;
  }

  public Person(String f, String l) {
    first = f;
    last = l;
  }

  public String toString() {
    return first + " " + last;
  }
}

The code above generates the following result.