2015-10-25 43 views
4

我有一些對象的列表。這些對象具有一些隨時間變化的領域和其他內容。我想要獲得某些值等於true的列表中的某些元素。我接受這個對象,並且我想在別的地方使用它。Java 8流更簡單

當列表不包含具有該元素的對象時,我得到一個異常,並且我的應用程序崩潰。所以我使用了一個非常奇怪的代碼來避免這種情況,並且我想知道,如果有什麼比這更簡單更好的東西。

public class CustomObject{ 
    private String name; 
    private boolean booleanValue; 
    //Getters and setters... 
} 

//Somewhere else I have the list of objects. 
List<CustomObject> customList = new ArrayList<>(); 
//Now... here I am using this strange piece of code I want to know how to change. 
if (customList.stream().filter(CustomObject::getBooleanValue).findAny().isPresent()) { 
    customList.stream().filter(CustomObject::getBooleanValue).findAny().get().... //some custom stuff here. 
} 

正如你所看到的,我在這裏做了非常難看的代碼:調用兩次相同的方法。 我想是這樣

CustomObject customObject = customList.stream().filter..... 

和檢查,如果該對象不爲空,但它沒有做什麼我想要的。

+1

你爲什麼不把'Optional'存儲在一個變量中? –

+0

因爲我不想用可選 –

+0

什麼?爲什麼?你已經在使用它了。 –

回答

8

你可以使用ifPresent擺脫isPresentget如果這是真的:

customList.stream() 
      .filter(CustomObject::getBooleanValue) 
      .findAny() 
      .ifPresent(customObject -> { /* do something here */ }); 

如果這個值是通過findAny()發現,特定的消費將被調用,否則,什麼都不會發生。

+0

謝謝,那真是我尋找的東西! –