2017-02-20 36 views
1

我想的foreach转换成流JAVA的foreach到流

for (Entity entity : listOfEntitys.getAll()) { 
     if (!isEntityDateValid(entity.getStartDate()) 
       || !isEntityDateValid(entity.getEndDate())) { 
      return false; 
     } 
    } 

所以我将它转换这样

if (listOfEntitys.getAll() != null) { 
     return listOfEntitys.getAll().stream().anyMatch(entity-> !isEntityDateValid(entity.getStartDate()) 
       || !isEntityDateValid(entity.getEndDate())); 
    } 

但我搞砸了,因为它的结果总是布尔值和我只在满足条件时才返回它

+0

条件返回语句不能更改为纯流,但如果您向我们展示更多代码,我们可能会帮助您 – ByeBye

+1

无需空检查,因为如果getAll返回null,for-each也会失败。 – john16384

回答

3

如果您只想在某些条件下返回,则您的流命令将需要成为if状态的一部分换货。

if (listOfEntities.getAll()!=null && listOfEntities.getAll().stream().anyMatch(...)) { 
    return false; 
} 

但它可能是使用!allMatch(X && Y)而非anyMatch(!X || !Y)清晰。

if (listOfEntities.getAll()!=null 
    && !listOfEntities.getAll().stream() 
      .allMatch(entity -> isEntityDateValid(entity.getStartDate()) 
        && isEntityDateValid(entity.getEndDate()))) { 
    return false; 
} 
0

你的错误就在于anyMatch返回true如果任何条目匹配您的条件:

return listOfEntitys.getAll().stream().anyMatch(entity-> !isEntityDateValid(entity.getStartDate()) 
      || !isEntityDateValid(entity.getEndDate())); 

所以在那里添加一个并不:

return !listOfEntitys.getAll().stream().anyMatch(entity-> !isEntityDateValid(entity.getStartDate()) 
      || !isEntityDateValid(entity.getEndDate())); 
0

所以它看起来像你有一个for循环,将如果所有日期都是有效的返回true,或者一旦不是返回false。
return true已丢失,但我想它已经存在了,否则您的初始翻译将无意义。

实现正确的方法是使用allMatch(),这是最准确地传达了循环的意思方法:

return listOfEntitys.getAll().stream() 
     .allMatch(e -> isEntityDateValid(e.getStartDate) || isEntityDateValid(e.getEndDate())); 

当且仅当所有实体具有有效日期这将返回true 。只要一个无效,它就返回false。就像你的for循环一样。

这还有一个额外的好处,它可以避免负面条件,这是一个更清晰的代码规则之一。