在集合中查找重复条目 [英] Finding duplicate entries in Collection
问题描述
是否有工具或程式库可根据可执行的特定条件在集合中查找重复条目?
Is there a tool or library to find duplicate entries in a Collection according to specific criteria that can be implemented?
为了说清楚:我想根据特定的标准将条目彼此进行比较。所以我认为谓词
只返回 true
或 false
isn
To make myself clear: I want to compare the entries to each other according to specific criteria. So I think a Predicate
returning just true
or false
isn't enough.
我不能使用 equals
。
推荐答案
我创建了一个类似于 -en-library / ms132151.aspx =nofollow> IEqualityComparer< T>
com /?q = .net%20frameworkrel =nofollow>。NET 。
I've created a new interface akin to the IEqualityComparer<T>
interface in .NET.
这样的 EqualityComparator< T>
Such a EqualityComparator<T>
I then pass to the following method which detects duplicates.
public static <T> boolean hasDuplicates(Collection<T> collection,
EqualsComparator<T> equalsComparator) {
List<T> list = new ArrayList<>(collection);
for (int i = 0; i < list.size(); i++) {
T object1 = list.get(i);
for (int j = (i + 1); j < list.size(); j++) {
T object2 = list.get(j);
if (object1 == object2
|| equalsComparator.equals(object1, object2)) {
return true;
}
}
}
return false;
}
这种方式我可以自定义比较我的需要。
This way I can customise the comparison to my needs.
这篇关于在集合中查找重复条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!