I'm trying to flatMap
Optional
s in Java. Here is a simplified example:
List<String> x = Arrays.asList("a", "b", "c");
List<String> result = x.stream().flatMap((val) -> val.equals("b") ? Optional.empty() : Optional.of(val)).collect(Collectors.toList());
I get this error message from the compiler:
Error:(10, 27) java: incompatible types: no instance(s) of type variable(s) T exist so that java.util.Optional<T> conforms to java.util.stream.Stream<? extends R>
What's wrong? Here is an example of what I'm trying to achieve in Scala:
List("a", "b", "c").flatMap(x => if (x == "b") None else Some(x))
It returns:
res2: List[String] = List(a, c)
as expected.
How do I convert this to Java so that it compiles?