Expected that
flatMap map the Stream input element to another Stream . Therefore, it should return Stream , not Optional .
Therefore, you should do something like this:
List<String> x = Arrays.asList("a", "b", "c"); List<Optional<String>> result = x.stream() .flatMap((val) -> val.equals("b") ? Stream.of(Optional.empty()) : Stream.of(Optional.of(val))) .collect(Collectors.toList());
Note that if your goal is simply to get rid of some values โโ("b" in your example), you do not have to use the "Advanced" parameter at all. You can simply filter the stream:
List<String> result = x.stream() .filter (val -> !val.equals("b")) .collect(Collectors.toList());
This way you don't need flatMap , but your output is List<String> instead of List<Optional<String>> .
As Holger noted, the solution that Stream of Optional returns can be simplified by using map instead of flatMap , since each element maps to one Optional :
List<String> x = Arrays.asList("a", "b", "c"); List<Optional<String>> result = x.stream() .map((val) -> val.equals("b") ? Optional.empty() : Optional.of(val)) .collect(Collectors.toList());
source share