【问题标题】:return about Java 8 forEach返回关于 Java 8 forEach
【发布时间】:2017-04-27 12:27:01
【问题描述】:
 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? 我尝试添加return false,如下所示:

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

不过是意料之外的表情,谁能帮我看看?

【问题讨论】:

  • 不使用forEach。当你想检查是否所有元素都满足一个条件时,你想使用allMatch。顺便说一句,您可以将您的预测试更改为 if(!aMap.keySet().equals(bMap.keySet()) return false; 这会检查超过地图的大小,并允许在您的条件下省略 null 测试。
  • 感谢您的快速回复
  • @Holger 你好,你能帮我回答stackoverflow.com/questions/43973596/…的问题吗

标签: foreach java-8


【解决方案1】:

你不能返回 false,因为你在一个实现 Consumer 函数接口的 lambda 表达式中,该方法是 void 类型。

改为使用 anyMatch 或 noneMatch 或 allMatch :

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

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

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

大多数时候打开{},这是一个好兆头,您应该创建一个新方法。

【讨论】:

  • 好吧,在这种情况下,您可以将表达式重写为不带大括号的形式,即x -> condition1 && condition2 && condition3 …,但它仍然太大,建议使用专用方法,特别是因为它会有更多通用,比较 AValueBValue 对象,这在其他地方也可能有用。
猜你喜欢
  • 2015-12-13
  • 2014-06-12
  • 2023-03-10
  • 1970-01-01
  • 2018-03-25
  • 2014-06-17
  • 2015-07-22
  • 1970-01-01
相关资源
最近更新 更多