首页 > 解决方案 > 按用户定义的字段集查找重复对象

问题描述

我的目标是在大约 500000 个对象和更多对象的列表中找到重复项。但是应该可以在运行时定义副本是什么。简单地说,应该可以通过这些对象的一组(更改的)用户定义字段来找到重复项。

我的方法

但这是一个好方法吗?我觉得样板文件太多了。还有更简单的吗?

限制:没有 SQL。

标签: java

解决方案


我在考虑这个问题,所以我想我会把我的评论建议变成一个实际的答案。

我只会创建一个BiPredicate<T, T>与请求的字段(在运行时)有关的,true如果它们与这些字段相等,则返回,false否则返回。

例如,假设您有以下类型:

public class YourType {
    private final String name;
    private final int age;
    private final int hatSize;
    // Constructors and getters omitted...
}

并且您想找到忽略的重复项hatSize,那么您可以编写如下内容:

public BiPredicate<YourType, YourType> makeChecker(
        final Collection<Function<YourType, ?>> fieldGetters) {
    // 'first' and 'second' are the two 'YourType' instances
    // to be compared
    return (first, second) -> {
        // Iterate over all the field getters
        for (final Function<YourType, ?> fieldGetter : fieldGetters) {
           // Retrieve the field values from each object
           final Object firstsField = fieldGetter.apply(first);
           final Object secondsField = fieldGetter.apply(second);

           // If they're not equal, break early
           if (!Objects.equals(firstsField, secondsField)) {
               return false;
           } 
        }
        // All of the requested properties were equal
        return true;
    };
}

并通过以下方式调用它:

makeChecker(Arrays.asList(YourType::getName, YourType::getAge));

然后,您可以在集合中执行任何正常的“删除重复项”方法,使用返回BiPredicate的 'test方法比较它们。


推荐阅读