使用Java8将数组迭代转换为Lambda函数 [英] Converting array iteration to lambda function using Java8

查看:315
本文介绍了使用Java8将数组迭代转换为Lambda函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换为Lambda函数

I am trying to convert to Lambda function

到目前为止,我已经能够将上述代码转换为如下所示的lambda函数

So far I am able to convert the above code to lambda function like as shown below

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函数中,我觉得它并不干净高效.

But still my goal was to avoid repeating the same logic and also to convert to Lambda function, still in my converted lambda function I feel its not clean and efficient.

这只是出于我的学习目的,我通过采用一个现有的代码片段来完成这些工作.

This is just for my learning aspect I am doing this stuff by taking one existing code snippet.

谁能告诉我如何即兴转换的Lambda函数

Can anyone please tell me how can I improvise the converted Lambda function

推荐答案

与@roookeee已经发布的方法类似,但可能更简洁一些:使用声明为:p的映射函数存储映射.

A similar approach as @roookeee already posted with but maybe slightly more concise would be to store the mappings using mapping functions declared as :

Function<String, Integer> extractEmployeeId = empId -> Integer.valueOf(empId.split("-")[2]);
Function<String, BigInteger> extractDate = empId -> new BigInteger(empId.split("-")[1]);

然后以以下方式进行映射:

then proceed with mapping as:

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相对应的接受或拒绝日期.

Hereafter you can also access the date of acceptance or rejection corresponding to the employeeId of the employee as well.

这篇关于使用Java8将数组迭代转换为Lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆