Java Collection How to - Remove Duplicates(Old Objects) from List








Question

We would like to know how to remove Duplicates(Old Objects) from List.

Answer

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/*w ww.j  a v  a2s . c om*/
public class Main {
  public static void main(String args[]) {
    MyObject c1 = new MyObject(1, "one");
    MyObject c2 = new MyObject(2, "two");
    MyObject c3 = new MyObject(3, "three");

    MyObject c4 = new MyObject(1, "one");
    MyObject c5 = new MyObject(2, "two");
    MyObject c6 = new MyObject(3, "three");

    Map<Integer, MyObject> map = new HashMap<Integer, MyObject>();
    map.put(c1.getId(), c1);
    map.put(c2.getId(), c2);
    map.put(c3.getId(), c3);
    map.put(c4.getId(), c4);
    map.put(c5.getId(), c5);
    map.put(c6.getId(), c6);

    System.out.println(map);
  }

}

class MyObject {
  public MyObject(int id, String name) {
    this.id = id;
    this.name = name;
    this.creationTme = new Date();
  }

  private Integer id;
  private String name;
  private Date creationTme;

  public int getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Date getCreationTme() {
    return creationTme;
  }

  public void setCreationTme(Date creationTme) {
    this.creationTme = creationTme;
  }

  @Override
  public int hashCode() {
    return this.id;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof MyObject && ((MyObject) obj).id == this.id)
      return true;
    else
      return false;
  }

  public String toString() {
    final String TAB = "    ";

    String retValue = "";

    retValue = "Check(" + "id = " + this.id + TAB + "name = " + this.name
        + TAB + "creationTme = " + this.creationTme.getTime() + TAB + " )";

    return retValue;
  }
}

The code above generates the following result.