问题
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