Joe Almore Joe Almore - 3 months ago 16
Java Question

Java - Find Element in Array using Condition and Lambda

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?

Answer

You can do it like this,

Optional<Present> optional = Arrays.stream(presents)
                                   .filter(x -> "MyString".equals(x.getName()))
                                   .findFirst();

if(optional.isPresent()) {//Check whether optional has element you are looking for
    Present p = optional.get();//get it from optional
}

You can read more about Optional here.

Comments