The key is how you identify two elements as being "equal". To do this, you'd need to override the equals
method from Object
. Then once your two elements are considered equals, you can use a variety of possible methods to remove duplicates: iterating, using a Set implementation (eg. TreeSet), and so forth.
Here's a minimal example for how you might go about this.
public class Record {
private String id;
private String name;
private int age;
// getters, setters, and constructor go here
@Override
public boolean equals(Object other) {
if(other == null || ! other instanceof Record) {
return false;
} else if (this == other) {
return true;
} else {
return this.name.equals(other.name) && this.age == other.age; // possible NPE if name is null, handle as appropriate
}
}
}
Now if you have two identical records, you can remove them:
Record bob1 = new Record(222, "Bob", 20);
Record bob2 = new Record(333, "Bob", 20);
Record bob3 = new Record(444, "Bob", 40);
bob1.equals(bob2); //true -> remove one
bob1.equals(bob3); //false
bob2.equals(bob3); //false
Note that if you override equals, you'll want to override hashCode
as well.
The problem with the data that you provided in your example is that the only differing characteristic between the two 20-year-old "Bob" records is the id number. Which one should be removed, 222 or 333?