【问题标题】:Is there a nice way to filter a list using streams and get a list of the items or null if no item passed the filter?有没有一种很好的方法来使用流过滤列表并获取项目列表,或者如果没有项目通过过滤器,则为 null?
【发布时间】:2020-05-05 07:53:36
【问题描述】:

目前我这样做:

List<MyObj> nullableList = myObjs.stream().filter(m -> m.isFit()).collect(Collectors.toList());
if (nullableList.isEmpty()) {
    nullableList = null;
}

有更好的方法吗?像 Collectors.toListOrNullIfEmpty() 这样的东西?

【问题讨论】:

  • 将 null 用作合法值并不是一个好习惯。特别是,null 绝不应用作空数组、集合或映射的同义词。使用空列表将允许其他代码省略空检查。

标签: java filter java-8 java-stream collectors


【解决方案1】:

没有这样的事情,你可以做一个辅助方法,基本上会:

.collect(
        Collectors.collectingAndThen(
            Collectors.toList(),
            x -> x.isEmpty() ? null : x)
);

但是你在这里自找麻烦。只需返回那个空列表而不是 null,除非您希望 调用者 最终讨厌您。

如果你真的很想要这样的收藏家:

static class PlzDont<T> implements Collector<T, List<T>, List<T>> {


    @Override
    public Supplier<List<T>> supplier() {
        return ArrayList::new;
    }

    @Override
    public BiConsumer<List<T>, T> accumulator() {
        return List::add;
    }

    @Override
    public BinaryOperator<List<T>> combiner() {
        return (left, right) -> {
            left.addAll(right);
            return left;
        };
    }

    @Override
    public Function<List<T>, List<T>> finisher() {
        return x -> x.isEmpty() ? null : x;
    }

    @Override
    public Set<Characteristics> characteristics() {
        return Set.of();
    }
}

【讨论】:

    【解决方案2】:

    我实际上不确定你必须这样做。有时人们编写可怕的代码试图使其更简单。我会在你的代码中留下额外的if 之后的情况。但是你可以在 c: 下找到你要找的代码:

    public class Demo {
    
        public static void main(String[] args) {
            List<Integer> list = Arrays.asList(1, 2, 3, 4);
            List<Integer> nullableList = list.stream()
                    .filter(m -> m > 2)
                    .collect(Collectors.collectingAndThen(
                            Collectors.toList(), filtered -> filtered.isEmpty() ? null : filtered
                    ));
            System.out.println(nullableList);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      相关资源
      最近更新 更多