java - 按用户定义的字段集查找重复对象
问题描述
我的目标是在大约 500000 个对象和更多对象的列表中找到重复项。但是应该可以在运行时定义副本是什么。简单地说,应该可以通过这些对象的一组(更改的)用户定义字段来找到重复项。
我的方法
- 为每个字段创建一个装饰器类
- 覆盖相等和哈希方法
- 创建所需的对象(可能只是字段颜色、颜色不齐、高度、宽度、重量)
- 查找重复项(不是这里的问题)
但这是一个好方法吗?我觉得样板文件太多了。还有更简单的吗?
限制:没有 SQL。
解决方案
我在考虑这个问题,所以我想我会把我的评论建议变成一个实际的答案。
我只会创建一个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
方法比较它们。
推荐阅读
- php - php字符串替换字符后#
- javascript - 如何访问 XMLHttpRequest 插入的 Dom 元素?
- xamarin - 发布版本中未触发命令
- php - 如何从 Symfony 中的数据库/实体中删除表?
- intellij-idea - 检查信息:验证@ConfigurationProperties 设置。2018.3 IntelliJ 中的新功能
- java - 编译失败;有关详细信息,请参阅编译器错误输出。asBitmap() 红色错误
- r - aa循环中的ifelse与R中的向量
- ssas - SQL Server Analysis Services 错误(数据挖掘)
- javascript - 美化大单行JSON文件
- python-3.x - 在 Tensorboard 中显示 Keras 图而不使用 fit 方法中的回调