javaarrayslambdajava-8java-stream

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?


Solution

  • You can do it like this,

    Optional<Preset> optional = Arrays.stream(presets)
                                      .filter(x -> "MyString".equals(x.getName()))
                                      .findFirst();
    
    // Check whether optional has element you are looking for
    if (optional.isPresent()) {
        Preset p = optional.get(); // Get it from optional
    }
    

    You can read more about Optional here.