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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With