应用功能后获取第一个元素并返回 [英] Getting first element and returning after apply a function
本文介绍了应用功能后获取第一个元素并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Java 8的新手,我想创建一个方法,该方法在应用函数后获取匹配的第一个元素并返回
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.
推荐答案
Optional.ifPresent
接受Consumer
,并且不返回任何值.使用map
:
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
或者按照Holger的建议,您可以将map
步骤移至流管道中:
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
这篇关于应用功能后获取第一个元素并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文