Getting first element and returning after apply a function

Sandro Rey :

I am new in Java 8, I want to make a method that gets the first element that matched and returning after apply a function

public void test() {
    List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");

    String str = features
            .stream()
            .filter(s -> "Lambdas".equals(s))
            .findFirst()
            .ifPresent(this::toLowerCase);
}

private String toLowerCase (String str) {
    return str.toLowerCase();
}

but I got an Incompatible types error.

Eran :

Optional.ifPresent accepts a Consumer, and doesn't return any value. Use map:

String str =
    features.stream()
            .filter(s -> "Lambdas".equals(s))
            .findFirst()
            .map(this::toLowerCase)
            .orElse(null); // default value or orElseThrow

Or, as Holger suggested, you can move the map step into the stream pipeline:

String str =
    features.stream()
            .filter(s -> "Lambdas".equals(s))
            .map(this::toLowerCase)
            .findFirst()
            .orElse(null); // default value or orElseThrow

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=122453&siteId=1