import java.util.*;
import java.util.stream.*;
class Demo {
Optional<Integer> parseInt(String s) {
try { return Optional.of(Integer.parseInt(s)); }
catch (NumberFormatException e) { return Optional.empty(); }
}
void example() {
var inputs = List.of("1", "two", "3", "four", "5");
// Old way — filter + get is ugly:
// .filter(Optional::isPresent).map(Optional::get)
//
// Java 9+ — flatMap with Optional::stream
List<Integer> nums = inputs.stream()
.map(this::parseInt)
.flatMap(Optional::stream)
.toList();
System.out.println(nums); // [1, 3, 5]
// First non-empty match
Optional<Integer> first = inputs.stream()
.map(this::parseInt)
.flatMap(Optional::stream)
.findFirst();
System.out.println(first); // Optional[1]
}
}
Create a free account and build your private vault. Share publicly whenever you want.