[英]Collector returning singletonList if toList returned empty list
I have quite a large stream pipeline and therefore would like to keep it clean. 我有一个很大的流管道,因此希望保持清洁。 I have the following part of larger pipeline
我有以下部分更大的管道
Integer defaultInt;
//...
Stream<Integer> ints;
ints.filter(/* predicate_goes_here */).collect(toSingletonIfEmptyCollector);
Where toSingletonIfEmptyCollector
is supposed to act the same as Collectors.toList()
does if it returns non-emtpy list and Collections.singletonList(defaultInt)
if Collectors.toList()
returned empty. 其中
toSingletonIfEmptyCollector
应该与Collectors.toList()
行为相同,如果它返回非emtpy列表,并且如果Collectors.toList()
返回空,则返回Collections.singletonList(defaultInt)
。
Is there a shorter way to implement it (eg by composing standard collectors provided in JDK) rather then implementing all Collector
's method from scratch? 是否有更短的方法来实现它(例如,通过组合JDK中提供的标准收集器)而不是从头开始实现所有
Collector
的方法?
You can use collectingAndThen
and perform an additional finisher operation on the built-in toList()
collector that will return a singleton list in case there was no elements. 您可以使用
collectingAndThen
和内置执行额外的整理操作toList()
收集器,将返回的情况下,有没有元素的单列表。
static <T> Collector<T, ?, List<T>> toList(T defaultValue) {
return Collectors.collectingAndThen(
Collectors.toList(),
l -> l.isEmpty() ? Collections.singletonList(defaultValue) : l
);
}
It would be used like this: 它会像这样使用:
System.out.println(Stream.of(1, 2, 3).collect(toList(5))); // prints "[1, 2, 3]"
System.out.println(Stream.empty().collect(toList(5))); // prints "[5]"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.