How can I remove all objects in a list that have the same ID?
For example in the following list:
Person person1 = new Person();
person1.setId("1");
Person person2 = new Person();
person2.setId("1"); //ie same as Person1
Person person3 = new Person();
person3.setId("2");
List<Person> PersonList = new ArrayList<>();
PersonList.add(person1);
PersonList.add(person2);
PersonList.add(person3);
My Method below works for the above but not when there are multiple duplicates, how can I solve this case also?
public List<Person> removeDuplicatesFromList(List<Person> personList){
for (int i = 0; i < personList.size(); i++) {
for (int j = i+1; j < personList.size(); j++) {
if(personList.get(i).getId().equalsIgnoreCase(personList.get(j).getId())){
personList.remove(personList.get(j));
}else{
}
}
}
return personList;
}