Java 8 stream more simple

I have a list of some objects. These objects have some fields and other things that change over time. I want to get certain elements inside a list that have a value equal to true. I take this object and I want to use it somewhere else.

When the list does not contain an object with this element, I get an exception and my application crashes. So I use really weird code to avoid this, and I want to know if there is something simpler and better than that.

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.
}

As you can see, I'm doing really ugly code here: calling twice the same method. I tried something like

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

and check if this object is not null, but it does not do what I wanted.

+4
1

ifPresent, isPresent get, :

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

findAny(), , .

+8

Source: https://habr.com/ru/post/1613113/


All Articles