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