首页 > 解决方案 > 在 Java 8 流的 filter() 和 map() 中使用相同的变量

问题描述

为了提高性能,我想在Java 8 流filter()map()Java 8 流中使用相同的变量。例子-

                list.stream()
                .filter(var -> getAnotherObject(var).isPresent())
                .map(var -> getAnotherObject(var).get())
                .collect(Collectors.toList())

被调用的方法getAnotherObject()看起来像 -

private Optional<String> getAnotherObject(String var)

在上述场景中,我必须调用该方法getAnotherObject()两次。
如果我使用常规的 for 循环,那么我只需要调用getAnotherObject()一次该方法。

List<String> resultList = new ArrayList<>();
        for(String var : list) {
            Optional<String> optionalAnotherObject = getAnotherObject(var);
            if(optionalAnotherObject.isPresent()) {
                String anotherObject = optionalAnotherObject.get();
                resultList.add(anotherObject)
            }
        }

即使使用流,我也可以将所有代码放入map()-

list.stream()
                .map(var -> {
                    Optional<String> anotherObjectOptional = getAnotherObject(var);
                    if(anotherObjectOptional.isPresent()) {
                        return anotherObjectOptional.get();
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

但我相信必须有一种优雅的方式使用filter().

标签: javafiltercollectionsjava-8java-stream

解决方案


你可以像这样创建一个流

list.stream()
        .map(YourClass::getAnotherObject)
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toList());

YourClass 指的getAnotherObject是定义方法的类的名称


推荐阅读