Java 8流更简单

Jan*_*ina 4 java java-8 java-stream

我有一些对象的列表.这些对象中有一些字段和其他内容随着时间的推移而变化.我希望列表中的某些元素具有某个值等于的值true.我拿这个对象,我想在其他地方使用它.

当列表不包含具有该元素的对象时,我得到一个异常,我的应用程序崩溃了.所以我使用一个非常奇怪的代码来避免这种情况,我想知道,如果有更简单,更好的东西.

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.
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我在这里做了非常丑陋的代码:调用两次相同的方法.我试过类似的东西

CustomObject customObject = customList.stream().filter..... 
Run Code Online (Sandbox Code Playgroud)

并检查该对象是否为空,但它没有做我想要的.

Tun*_*aki 8

您可以使用它ifPresent来摆脱它isPresent,get如果它是真的:

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

如果找到了值findAny(),则将调用指定的使用者,否则不会发生任何事情.