2017-02-20 38 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循環一樣。

這還有一個額外的好處,它可以避免負面條件,這是一個更清晰的代碼規則之一。