需求
根据从另一个微服务取到的用户自定义过滤规则,完成实体的去重,并返回给调用方进行后续更新操作
规则定义非常灵活:不同实体类型有不同的过滤规则,且过滤规则的过滤字段数目不定、指定字段名称不定
参考
https://blog.csdn.net/Draymond_feng/article/details/108304165
list<Bean> java8根据某几个属性去重
实现
/**
* 根据传入的属性列表返回去重字段的Function
*
* Function<CustomRecord, String> : 传入CustomRecod,返回String
* function.apply(t),其中t就是CustomRecord
*
* 入参为所有要过滤的属性字段
*
* @return
*/
public static Function<CustomRecord, String> distinctByKeyFunction(List<String> fields) {
return (CustomRecord customRecord) -> {
// sj的写法,无需处理最后一个尾缀
StringJoiner sj = new StringJoiner("-");
for (String field : fields) {
sj.add(customRecord.getFieldValue(field));
}
return sj.toString();
};
}
/**
* 根据传入的function进行断言
*
* @return
*/
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> function) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(function.apply(t), Boolean.TRUE) == null;
}
public void diffAndMerge(Input inputArgs) {
// ...
// updateDetails就是包含了大量重复数据的List<CustomRecord>
updateDetails.addAll(toDoDetails);
// 首先按照实体类型进行分类,因为不同实体配置了不同的过滤规则
Map<String, List<CustomRecord>> recordByType = updateDetails.stream().collect(
Collectors.groupingBy(CustomRecord::getEntityName));
for (String entityName : recordByType.keySet()) {
// 获取全量的唯一性校验规则
List<EntityDuplicateCheck> checks = otherPSM
.getCheck(RequestContext.getSystemCode(), CommonConstants.SYS_NAME,
entityName);
// 过滤无法处理的唯一性校验规则
checks = checks.stream()
.filter(entityDuplicateCheck -> Objects.nonNull(entityDuplicateCheck) && Objects
.nonNull(entityDuplicateCheck.getGroups())).collect(Collectors.toList());
for (EntityDuplicateCheck check : checks) {
List<String> properties = new ArrayList<>();
// 获取所有的校验规则
check.getRuleGroups().stream()
.filter(ruleGroup -> Objects.nonNull(ruleGroup) && Objects
.nonNull(ruleGroup.getFields())).forEach(
ruleGroup -> properties
.addAll(ruleGroup.getFields().stream().filter(Objects::nonNull)
.map(RuleField::getFieldName)
.collect(Collectors.toList())));
// 根据指定属性进行过滤,获取当前规则去重后的结果
// distinctByKey(distinctByKeyFunction(properties)遵循函数式编程,distinctByKey的入参是一种过滤规范,distinctByKeyFunction是具体的过滤方案,入参是List<String>
List<CustomRecord> uniqueRecord = updateDetails.stream()
.filter(distinctByKey(distinctByKeyFunction(properties))).collect(Collectors.toList());
updateDetails = uniqueRecord;
}
}
}
updateRecord.setDetails(updateDetails.stream().distinct().collect(Collectors.toList()));
}