问题描述
我有一个自定义对象的ArrayList。我想删除重复的条目。
I have an ArrayList of custom objects. I want to remove duplicate entries.
对象有三个字段: title,subtitle
和 id
。如果一个字幕多次出现,我只需要第一个带有那个副标题的项目(忽略带有该副标题的剩余对象)。
The objects have three fields: title, subtitle
, and id
. If a subtitle occurs multiple times, I only need the first item with thats subtitle (ignore the remaining object with that subtitle).
推荐答案
您可以使用自定义Comparator将ArrayList的内容放入TreeSet中,如果两个字幕是相同。
之后,您可以转换列表中的Set并使列表没有重复。
这是Object的一个例子,当然你应该使用正确的类和逻辑。
You can put the content of the ArrayList in a TreeSet using a custom Comparator which should return 0 if the two subtitles are the same.After that you can convert the Set in a List and have the List without "duplicates".Here is an example for Object, of course you should use the correct class and logic.
public void removeDuplicates(List<Object> l) {
// ... the list is already populated
Set<Object> s = new TreeSet<Object>(new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
// ... compare the two object according to your requirements
return 0;
}
});
s.addAll(l);
List<Object> res = Arrays.asList(s.toArray());
}
这篇关于从ArrayLists中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!