If your classes have a correct implementation of the equals and hashCode method, turn the list into a HashSet to eliminate the duplicates. The HashSet<T> constructor accepts a Collection<T> so you should be good to go.
If you need some custom comparator function (like the one in your case which compares only id), pass in a custom Comparator<T> implementation when creating the TreeSet. To sum it up, just create a comparator which compares ids of both the objects and pass it to the TreeSet constructor. Then adding items from both the lists to this set will take care of eliminating the duplicates. Something like:
public class Test {
public static void main(String[] args) {
Person p1 = new Person("first", "id1");
Person p2 = new Person("dummy", "id1"); // same id as above
Person p3 = new Person("second", "id2");
Person p4 = new Person("third", "id1");
List<Person> asList = Arrays.asList(p1, p2, p3, p4);
CustomComparator comparator = new CustomComparator();
TreeSet<Person> ts = new TreeSet<Person>(comparator);
TreeSet<Person> duplicates = new TreeSet<Person>(comparator);
for (Person p : asList) {
if (ts.contains(p) || duplicates.contains(p)) {
duplicates.add(p);
ts.remove(p);
} else {
ts.add(p);
}
}
System.out.println(ts);
}
}
class Person {
public Person(String name, String id) {
super();
this.name = name;
this.id = id;
}
public String name;
public String id;
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [id=");
builder.append(id);
builder.append(", name=");
builder.append(name);
builder.append("]");
return builder.toString();
}
}
class CustomComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
return o1.id.compareTo(o2.id);
}
}