我有几个方法,除了在这些方法中调用的一个方法之外,它们基本上都是相同的。
示例:
protected List < DeadlineEntity > getEntityOneDeadlines() {
return deadLineEntityList
.stream()
.filter(m - > getEntityOneDeadlineDbs().stream().anyMatch(p - > m.getDb_4() != null && m.getDb_4().equals(p)))
.collect(Collectors.toList());
}
protected List < DeadlineEntity > getEntityTwoDeadlines() {
return deadLineEntityList
.stream()
.filter(m - > getEntityTwoDeadlineDbs().stream().anyMatch(p - > m.getDb_5() != null && m.getDb_5().equals(p)))
.collect(Collectors.toList());
}
所以唯一的区别是方法getDB()
。
由于我不想使用这个方法 10 次,所以我想到将其写入一个方法中,然后通过输入参数来控制它。
我的尝试如下:
protected List < DeadLineEntity > getDeadlines(List < Integer > deadLineDbList, Function << ? super T, ? > dbProperty) {
return deadLineEntityList
.stream()
.filter(m - > deadLineDbList.stream().anyMatch(p - > ....))
}
在方法 anymatch()
中,我没有进一步了解。
这就是我想要使用它的方式:
List<DeadlineEntity> list1 = getDeadlines(getEntityOneDeadlineDbs(), EntityOne::getDb_4());
List<DeadlineEntity> list2 = getDeadlines(getEntityTwoDeadlineDbs(), EntityTwo::getDb_5());
你觉得怎么样?这是一个好方法吗?
getDeadlines()
方法中的进一步过程是什么
最佳答案
只需使用 Supplier
插入所需的 List
实例和 Function
来替换 DeadlineEntity
中的 getter到 T
兼容 getEntityXXX
方法返回的 List 的泛型类型:
protected <T> List<DeadlineEntity> getDeadlines(Supplier<List<T>> dbProperty, Function<DeadlineEntity, T> getter) {
return deadLineEntityList
.stream()
.filter(m -> dbProperty.get()
.stream()
.anyMatch(p -> getter.apply(m) != null &&
getter.apply(m).equals(p)))
.collect(Collectors.toList());
}
List<DeadlineEntity> one = getDeadlines(this::getEntityOneDeadlineDbs, DeadlineEntity::getDb_4);
List<DeadlineEntity> two = getDeadlines(this::getEntityTwoDeadlineDbs, DeadlineEntity::getDb_5);
编辑:为了使代码更具可读性,我首先过滤掉所有等于 null
的 p
,然后简化 lambda 表达式并切换anyMatch
方法中的 equals
调用是空安全的:
protected <T> List<DeadlineEntity> getDeadlines(Supplier<List<T>> dbProperty, Function<DeadlineEntity, T> getter) {
return deadLineEntityList
.stream()
.filter(m -> dbProperty.get().stream()
.filter(Objects::nonNull)
.anyMatch(p -> p.equals(getter.apply(m))))
.collect(Collectors.toList());
}
关于java - 有没有一种方法可以使用 Function< 将多个方法减少为一个方法? super T, ?> 作为方法参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67329520/