仅Java 8 collect()isPresent()可选值 [英] Java 8 collect() only isPresent() Optional values

查看:218
本文介绍了仅Java 8 collect()isPresent()可选值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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()可选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆