In short, I have this code, and I'd like to get an specific element of the array using a condition and lambda. The code would be something like this:
Preset[] presets = presetDALC.getList();
Preset preset = Arrays.stream(presets).select(x -> x.getName().equals("MyString"));
But obviously this does not work. In C# would be something similar but in Java, how do I do this?
You can do it like this,
You can read more about
Optional
here.Like this:
This will return an
Optional
which might or might not contain a value. If you want to get rid of theOptional
altogether:The
filter()
operation is an intermediate operation which returns a lazy stream, so there's no need to worry about the entire array being filtered even after a match is encountered.Do you want first matching, or all matching?
Output