【问题标题】:Collector returning singletonList if toList returned empty list如果 toList 返回空列表,则收集器返回 singletonList
【发布时间】:2016-11-20 22:38:51
【问题描述】:

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

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

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

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

【问题讨论】:

  • 我假设你不会改变结果列表。
  • IntStreamStream&lt;Integer&gt; 中可能有很多帮助方法。 注意: IntStream 是一个原始流(只是一个小提示)

标签: java java-8 java-stream collectors


【解决方案1】:

您可以使用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]"

【讨论】:

  • 我宁愿用更具体的名称命名自定义收集器,例如 toListOrDefault,特别是它是静态的,害怕与 Collectors.toList 混淆,特别是在使用静态导入的情况下。
猜你喜欢
  • 2018-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 1970-01-01
  • 2020-01-31
  • 2018-12-03
相关资源
最近更新 更多