Java 8 collect() 仅 isPresent() 可选值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39920542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:33:29  来源:igfitidea点击:

Java 8 collect() only isPresent() Optional values

javajava-8java-streamoptional

提问by ?????????s

Is there a more elegant way of practically achieving this in Java 8?

在 Java 8 中是否有更优雅的方法来实际实现这一点?

list.stream()
    .map(e -> myclass.returnsOptional(e))
    .filter(Optional::isPresent)
    .map(Optional::get)
    .collect(Collectors.toList());

I'm talking about filter(Optional::isPresent)followed by map(Optional::get), I want to elegantly collect in a list only Optionalresults which have a value.

我说的是filter(Optional::isPresent)后跟map(Optional::get),我想优雅地将仅Optional具有值的结果收集在列表中。

回答by Amin J

Not sure if its so different but you could just filter based on your optional instead of getting the optional and filtering next. Something like this?

不确定它是否如此不同,但您可以根据您的可选项进行过滤,而不是接下来获取可选项和过滤。像这样的东西?

list.stream()
    .filter(e -> myclass.returnsOptional(e).isPresent())
    .collect(Collectors.toList());

Note: This will only work if returnsOptional returns the same object type as your original list item types.

注意:这仅在returnsOptional 返回与原始列表项类型相同的对象类型时才有效。

回答by eGoLai

In your case you can use one flatMapinstead of combinations of mapfilterand 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.

你的情况,你可以使用一个flatMap替代的组合mapfilter和再次map。要做到这一点,最好定义一个单独的函数来创建一个流:public private static Stream<Integer> createStream(String e)在 lambda 表达式中不要有几行代码。

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();
        }
    }
}

in case returnsOptional cannot be static you will need to use "arrow" expression instead of "method reference"

如果returnsOptional不能是静态的,您将需要使用“箭头”表达式而不是“方法引用”