我有一个带有自定义对象的ArrayList。我想要的是根据自定义对象的name属性从数组中删除重复项。我曾尝试使用Set person = new TreeSet()来完成此操作;但它不起作用。我猜是因为set比较的是地址或其他东西,而不是name属性。因此,我现在尝试使用迭代器,它也不会删除重复项。这就是我得到的;
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());
}虽然我在ArrayList中看到了重复的内容,但它没有被修改。我需要些帮助。谢谢!
发布于 2013-05-22 20:03:05
我也遇到了同样的情况,于是我想出了一个使用SortedSet的解决方案。在这种情况下,那些导致Set的比较器返回0的对象将只在Set中插入一次。
下面是一个示例:
SortedSet<Person> persons = new TreeSet<Person>(new Comparator<Person>() {
@Override
public int compare(Person arg0, Person arg1) {
return arg0.getName().compareTo(arg1.getName());
}
});现在,如果您在persons中插入一个Person,则不会插入重复项(基于其name属性)。
因此,您可以迭代list<Person>并将其中的每一项插入到persons集合中,并确保不会有任何重复项。所以剩下的就像这样:
Iterator<Person> iterator = people.iterator();
while(iterator.hasNext()) {
persons.add(iterator.next());
}
people.clear();
people.addAll(persons); //Now, your people does not contain duplicate nameshttps://stackoverflow.com/questions/16691067
复制相似问题