【发布时间】:2020-09-11 20:18:59
【问题描述】:
我正在学习 Java 8 功能接口并尝试了一些示例。 我正在尝试创建一种方法,该方法将接受通用列表作为一个参数,并将字符串数据过滤器参数作为另一个参数。 下面的代码按预期工作,但是当我尝试将 Predicate 转换为 Lambda 表达式时,我遇到了困难。
@SuppressWarnings("unchecked")
public static <T> List<T> filter_and_find_only_selected_Data1(List<T> genericList, String dataFilter){
Stream<List<T>> list = genericList.stream().map(eachListObj-> {
if(eachListObj instanceof Employee){
return genericList.stream().filter((Predicate<? super T>) new Predicate<Employee>() {
public boolean test(Employee eachEmpObj) {
return eachEmpObj.getEmpDept().equalsIgnoreCase(dataFilter);
}
}).collect(Collectors.toList());
}else if(eachListObj instanceof Customer){
return genericList.stream().filter((Predicate<? super T>) new Predicate<Customer>(){
public boolean test(Customer eachCust) {
return !eachCust.getCustomerName().equalsIgnoreCase(dataFilter);
}
}).collect(Collectors.toList());
}
return null;
});
return list.findAny().get();
}
有什么办法,我可以将谓词转换为 Lambda,如果有办法,我可以将 if-else-if 转换为三元运算符。 比如:(if condition)?return Value:(else-if condition):return value:null;
【问题讨论】:
-
接受任意
T的“通用”方法没有多大意义,但只有当T实际上是两个不相关的具体类型之一时才会做一些有用的事情。