如果toList返回空列表,则收集器返回singletonList

时间:2016-07-18 10:45:34

标签: java java-8 java-stream collectors

我有一个很大的流管道,因此希望保持清洁。我有以下部分的大型管道

Integer defaultInt;
//...
Stream<Integer> ints;
ints.filter(/* predicate_goes_here */).collect(toSingletonIfEmptyCollector);

toSingletonIfEmptyCollectorCollectors.toList()的行为相同,如果它返回非emtpy列表,Collections.singletonList(defaultInt)如果Collectors.toList()返回空的话。

是否有更短的方法来实现它(例如,通过编写JDK中提供的标准收集器)而不是从头开始实现所有Collector的方法?

1 个答案:

答案 0 :(得分:16)

您可以使用collectingAndThen并对内置toList()收集器执行额外的修整器操作,以便在没有元素的情况下返回单例列表。

static <T> Collector<T, ?, List<T>> toList(T defaultValue) {
    return Collectors.collectingAndThen(
              Collectors.toList(), 
              l -> l.isEmpty() ? Collections.singletonList(defaultValue) : l
           );
}

它会像这样使用:

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]"
相关问题