Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream more simple

I have a list of some objects. Those objects have some fields and other stuff inside that changes over time. I want to get certain elements inside the list that have some value equal to true. I take that object and I want to use it somewhere else.

When the list doesn't contain an object with that element, I get an exception and my application crashes. So I am using a really strange code to avoid this and I want to know, if there is something more simple and better than this.

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 am doing really ugly code here: calling twice the same method. I tried something like

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

and checking if that object is not null but it is not doing what I wanted.

like image 946
Jan Doomwalkerx Peřina Avatar asked Feb 08 '23 17:02

Jan Doomwalkerx Peřina


1 Answers

You can just use ifPresent to get rid of isPresent and get if it is true:

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

If a value was found by findAny(), the specified consumer will be invoked, otherwise, nothing will happen.

like image 143
Tunaki Avatar answered Feb 15 '23 12:02

Tunaki