Joe Almore Joe Almore - 1 year ago 109
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 = -> 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 Source

You can do it like this,

Optional<Present> optional =
                                   .filter(x -> "MyString".equals(x.getName()))

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download