Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing element from arraylist depending on a custom object property

I have an ArrayList with custom objects. What i want is to remove the duplicates from the array depending on the name property of the custom object. I have tried to accomplish this with Set person = new TreeSet(); but it's not working. I guess because the set is comparing addresses or something else than the name property. So i'm now trying to use an iterator which is not removing the duplicates either. This is what i got;

ArrayList<Person> people = new ArrayList<Person>();
Iterator<Person> iterator = people.iterator();
while (iterator.hasNext()) {
   Person person = iterator.next();

   if (person.getName().equals(iterator.next().getName())) {
       iterator.remove();
   }
}
for (Person person : people) {
    System.out.println(person.getName());
}

The ArrayList is not being modified though i see duplicates in it. I need some help. Thanks!

like image 203
madcoderz Avatar asked May 22 '13 11:05

madcoderz


1 Answers

I had the same situation, and I came up with this solution to use SortedSet. In this case, those objects which cause set's comparator to return 0, will only be inserted once in the Set.

Here is an example:

SortedSet<Person> persons = new TreeSet<Person>(new Comparator<Person>() {
    @Override
    public int compare(Person arg0, Person arg1) {
        return arg0.getName().compareTo(arg1.getName());
    }
});

And now if you insert a Person into your persons, the duplicates (based on their name property) will not be inserted.

So you can iterator over your list<Person> and insert every item of it into your persons set, and be sure that you will not have any duplicates. So the rest would be like:

Iterator<Person> iterator = people.iterator();
while(iterator.hasNext()) {
    persons.add(iterator.next());
}
people.clear();
people.addAll(persons); //Now, your people does not contain duplicate names
like image 84
Matin Kh Avatar answered Oct 16 '22 09:10

Matin Kh