在集合中查找重复条目 [英] Finding duplicate entries in Collection

查看:87
本文介绍了在集合中查找重复条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有工具或程式库可根据可执行的特定条件在集合中查找重复条目?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆