返回Java 8 forEach [英] return about Java 8 forEach

查看:281
本文介绍了返回Java 8 forEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 Boolean isSuccess = true;
    if(aMap.size() != bMap.size())
    {
        return false;
    }

    aMap.entrySet().forEach(entry -> {
        AKey aKey = entry.getKey();
        BValue bValue = bMap.get(aKey);

        if(bValue == null)
            return;

        AValue aValue = entry.getValue();
        if(!aValue.getClosed().equals(bValue.getClosed()))
            return;

        if(!aValue.getClosedToArrival().equals(bValue.getClosedToArrival()))
            return;

        if(!aValue.getClosedToDeparture().equals(bValue.getClosedToDeparture()))
            return;

        if(!aValue.getLengthOfStayArrival().equals(bValue.getLengthOfStayArrival()))
            return;
    });

    return isSuccess;

验证失败时如何返回false?
i试图添加返回false,如下所示:

How can i return false when validation failure? i tried to add return false, such as below:

if(!aValue.getLengthOfStayArrival().equals(bValue.getLengthOfStayArrival()))
        return false; 

但这是意料之外的表情,谁能帮我看看?

but it is unexpected expression, who can help me have a look?

推荐答案

您不能返回false,因为您在lambda表达式中实现了Consumer函数接口,该方法属于void类型。

You can't return false because you are in a lambda expression which implement the Consumer functional interface which method is of void type.

相反,请使用anyMatch或noneMatch或allMatch:

Instead, use anyMatch or noneMatch or allMatch :

return aMap.entrySet().stream().anyMatch(entry -> {
    return false;// Put your condition here 
});

我还建议在方法中提取验证,以便管道看起来像这样:

I would also recommend to extract the validation in a method so that your pipeline looks like this :

return aMap.entrySet()
           .stream()
           .anyMatch(this::checkIfMatch);

大部分时间打开 {} ,这是一个很好的迹象,你应该创建一个新的方法。

Most of the times when opening {}, it's a good sign that you should create a new method.

这篇关于返回Java 8 forEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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