有没有一种很好的方法来使用流过滤列表并获取项目列表,或者如果没有项目通过过滤器则为 null?
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?
目前我是:
List<MyObj> nullableList = myObjs.stream().filter(m -> m.isFit()).collect(Collectors.toList());
if (nullableList.isEmpty()) {
nullableList = null;
}
有更好的方法吗?像 Collectors.toListOrNullIfEmpty()?
实际上我不确定您是否必须这样做。有时人们会写出糟糕的代码试图让它变得更简单。我会像在您的代码中一样在流后留下额外的 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);
}
}
没有这样的事情,你可以做一个基本上会的辅助方法:
.collect(
Collectors.collectingAndThen(
Collectors.toList(),
x -> x.isEmpty() ? null : x)
);
可是你这是自找麻烦。只是 return 那个空列表而不是 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();
}
}
目前我是:
List<MyObj> nullableList = myObjs.stream().filter(m -> m.isFit()).collect(Collectors.toList());
if (nullableList.isEmpty()) {
nullableList = null;
}
有更好的方法吗?像 Collectors.toListOrNullIfEmpty()?
实际上我不确定您是否必须这样做。有时人们会写出糟糕的代码试图让它变得更简单。我会像在您的代码中一样在流后留下额外的 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);
}
}
没有这样的事情,你可以做一个基本上会的辅助方法:
.collect(
Collectors.collectingAndThen(
Collectors.toList(),
x -> x.isEmpty() ? null : x)
);
可是你这是自找麻烦。只是 return 那个空列表而不是 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();
}
}