java123999
java123999

Reputation: 7394

Remove Objects with a duplicate ID from a list?

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;
    }

Upvotes: 0

Views: 2281

Answers (2)

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

Like @tobias_k already commented, I suggest you to use Map<String, Person> instead of List<Person>. This will avoid duplicates in the first place, so that there is no need to remove them.

Your modified code would like this:

Person person1 = new Person();
person1.setId("1");

Person person2 = new Person();
person2.setId("1"); //i.e. same as person1

Person person3 = new Person();
person3.setId("2");

Map<String, Person> personMap = new HashMap<>();
personMap.put(person1.getId(), person1);
personMap.put(person2.getId(), person2);
personMap.put(person3.getId(), person3);

Calling personMap.get("1") then would give person2, and personMap.get("2") would give person3.

Upvotes: 2

thebishal
thebishal

Reputation: 71

You can make use of Map. Use key as person id and person object as value

public List<Person> removeDuplicatesFromList(List<Person> personList){
   Map<String, Person> map = new HashMap<String, Person>();
   List<Person> newPersonList = new ArrayList<>();
   for(Person p:personList){
       map.put(p.getId(),p);
   }
   Iterator itr=map.keySet().iterator();
   while (itr.hasNext()) {
     String id =  itr.next().toString();
     newPersonList.add((Person)map.get(id));
    }
  return newPersonList;
 }

Upvotes: 1

Related Questions