目前我做的是:
List<MyObj> nullableList = myObjs.stream().filter(m -> m.isFit()).collect(Collectors.toList());
if (nullableList.isEmpty()) {
nullableList = null;
}
还有更好的方法吗?像 Collectors.toListOrNullIfEmpty() 这样的东西?
最佳答案
不存在这样的事情,你可以做一个辅助方法,基本上可以:
.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();
}
}
关于java - 有没有一种很好的方法来使用流过滤列表并获取项目列表或如果没有项目通过过滤器则获取 null ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59804080/