简体   繁体   中英

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?

You can do it like this,

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

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

You can read more about Optional here .

Like this:

Optional<Preset> preset = Arrays
        .stream(presets)
        .filter(x -> x.getName().equals("MyString"))
        .findFirst();

This will return an Optional which might or might not contain a value. If you want to get rid of the Optional altogether:

Preset preset = Arrays
        .stream(presets)
        .filter(x -> x.getName().equals("MyString"))
        .findFirst()
        .orElse(null);

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?

String[] presets = {"A", "B", "C", "D", "CA"};

// Find all matching
List<String> resultList = Arrays.stream(presets)
                                .filter(x -> x.startsWith("C"))
                                .collect(Collectors.toList());
System.out.println(resultList);

// Find first matching
String firstResult = Arrays.stream(presets)
                           .filter(x -> x.startsWith("C"))
                           .findFirst()
                           .orElse(null);
System.out.println(firstResult);

Output

[C, CA]
C

One-liner since Java 8:

Preset found = Stream.of(presets)
    .filter(p -> p.getName().equals("MyString"))
    .findFirst().orElseThrow();

Avoid declaring Optional<>, that returned from findFirst as a variable or a parameter. It is designed for return types / "one-liner" styles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM