In your case you can use one flatMap
instead of combinations of map
filter
and again map
.
To Do that it's better to define a separate function for creating a Stream: public private static Stream createStream(String e)
to not have several lines of code in lambda expression.
Please see my full Demo example:
public class Demo{
public static void main(String[] args) {
List list = Arrays.asList("1", "2", "Hi Stack!", "not", "5");
List newList = list.stream()
.flatMap(Demo::createStream)
.collect(Collectors.toList());
System.out.println(newList);
}
public static Stream createStream(String e) {
Optional opt = MyClass.returnsOptional(e);
return opt.isPresent() ? Stream.of(opt.get()) : Stream.empty();
}
}
class MyClass {
public static Optional returnsOptional(String e) {
try {
return Optional.of(Integer.valueOf(e));
} catch (NumberFormatException ex) {
return Optional.empty();
}
}
}
in case returnsOptional cannot be static you will need to use "arrow" expression instead of "method reference"