Getting first element and returning after apply a function

末鹿安然 提交于 2021-02-04 16:18:25

问题


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.


回答1:


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



回答2:


 String str =
        features
            .stream()
            .filter("Lambdas"::equals)
            .findFirst()
            .map(this::toLowerCase)
            .orElse("AnythingElse");

findFirst returns an Optional, as such use some method on that Optional, like orElse that would return some String instance.

Look closely at what Optional::ifPresent takes as input - it's a Consumer, thus read it as "take that String as input, do something with it and return nothing".




回答3:


You can map the string if found orElse assign null to it:

List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
String str = features
        .stream()
        .filter(s -> "Lambdas".equals(s))
        .findFirst()
        .map(String::toLowerCase)
        .orElse(null);


来源:https://stackoverflow.com/questions/56965311/getting-first-element-and-returning-after-apply-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!