使用Java8将数组迭代转换为lambda函数
作者:互联网
我想转换为Lambda函数
到目前为止,我能够将上面的代码转换为lambda函数,如下所示
Stream.of(acceptedDetails, rejectedDetails)
.filter(list -> !isNull(list) && list.length > 0)
.forEach(new Consumer<Object>() {
public void accept(Object acceptedOrRejected) {
String id;
if(acceptedOrRejected instanceof EmployeeValidationAccepted) {
id = ((EmployeeValidationAccepted) acceptedOrRejected).getId();
} else {
id = ((EmployeeValidationRejected) acceptedOrRejected).getAd().getId();
}
if(acceptedOrRejected instanceof EmployeeValidationAccepted) {
dates1.add(new Integer(id.split("something")[1]));
Integer empId = Integer.valueOf(id.split("something")[2]);
empIds1.add(empId);
} else {
dates2.add(new Integer(id.split("something")[1]));
Integer empId = Integer.valueOf(id.split("something")[2]);
empIds2.add(empId);
}
}
});
但我的目标仍然是避免重复相同的逻辑并转换为Lambda函数,仍然在我转换的lambda函数中我觉得它不干净和高效.
这只是为了我的学习方面,我正在通过一个现有的代码片段来做这件事.
任何人都可以告诉我如何即兴改变Lambda函数
解决方法:
与@roookeee类似的方法已经发布但可能稍微简洁一点,就是使用声明为的映射函数来存储映射:
Function<String, Integer> extractEmployeeId = empId -> Integer.valueOf(empId.split("-")[2]);
Function<String, BigInteger> extractDate = empId -> new BigInteger(empId.split("-")[1]);
然后继续映射为:
Map<Integer, BigInteger> acceptedDetailMapping = Arrays.stream(acceptedDetails)
.collect(Collectors.toMap(a -> extractEmployeeId.apply(a.getId()),
a -> extractDate.apply(a.getId())));
Map<Integer, BigInteger> rejectedDetailMapping = Arrays.stream(rejectedDetails)
.collect(Collectors.toMap(a -> extractEmployeeId.apply(a.getAd().getId()),
a -> extractDate.apply(a.getAd().getId())));
此后,您还可以访问与员工employeeId相对应的接受或拒绝日期.
标签:functional-interface,java,java-8,lambda,functional-programming 来源: https://codeday.me/bug/20190823/1696806.html