问题描述
在Java 8中,有没有更优雅的方法来实际实现这一目标?
Is there a more elegant way of practically achieving this in Java 8?
list.stream()
.map(e -> myclass.returnsOptional(e))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
我说的是filter(Optional::isPresent)
,然后是map(Optional::get)
,我想只在列表中优雅地收集具有值的Optional
结果.
I'm talking about filter(Optional::isPresent)
followed by map(Optional::get)
, I want to elegantly collect in a list only Optional
results which have a value.
推荐答案
在您的情况下,您可以使用一个flatMap
代替map
filter
再使用map
的组合.为此,最好定义一个单独的函数来创建Stream:public private static Stream<Integer> createStream(String e)
在lambda表达式中不要有几行代码.
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<Integer> 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<String> list = Arrays.asList("1", "2", "Hi Stack!", "not", "5");
List<Integer> newList = list.stream()
.flatMap(Demo::createStream)
.collect(Collectors.toList());
System.out.println(newList);
}
public static Stream<Integer> createStream(String e) {
Optional<Integer> opt = MyClass.returnsOptional(e);
return opt.isPresent() ? Stream.of(opt.get()) : Stream.empty();
}
}
class MyClass {
public static Optional<Integer> returnsOptional(String e) {
try {
return Optional.of(Integer.valueOf(e));
} catch (NumberFormatException ex) {
return Optional.empty();
}
}
}
万一returnsOptional不能为静态,则需要使用箭头"表达式代替方法引用"
in case returnsOptional cannot be static you will need to use "arrow" expression instead of "method reference"
这篇关于仅Java 8 collect()isPresent()可选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!