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;
}
List<CustomObject> customList = new ArrayList<>();
if (customList.stream().filter(CustomObject::getBooleanValue).findAny().isPresent()) {
customList.stream().filter(CustomObject::getBooleanValue).findAny().get()....
}
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.