仅当流不是空后缀时,自定义收集器才在分隔符、后缀和前缀上加入流

2022-01-22 00:00:00 java java-stream collectors

我有一个字符串流:

流<字符串>流 = ...;

我想创建一个字符串使用

I want to create a string using

stream.collect(Collectors.joining(',', '[', ']'))

只有我想返回无字符串"如果流不包含任何元素.

only I want to return "No Strings" if the stream does not contain any elements.

我注意到 String java.util.stream.Stream.collect(Collector collector)方法接受类型为 java.util.stream.Collector

I notice that String java.util.stream.Stream.collect(Collector<? super String, ?, String> collector) method takes an argument of type java.util.stream.Collector<T, A, R>

对于我的项目,我在很多地方都需要这个功能,所以我需要一个实现 Collector 接口的类.

For my project I need to this functionality in many places so I would need a class the implements the Collector interface.

我知道这可以通过 Stream to a List 然后检查 List.size() == 0 来完成?然后根据需要再次将列表转换为流.

I know this could be done by Stream to a List and then checking on List.size() == 0? and then convert the list to a stream again if needed.

List<String> list = stream.collect(Collectors.toList());

if (list.size() == 0) {
    return "No Strings";
}
return list.stream().collect(Collectors.joining(",", "[", "]"));`

这就是我想要发生的事情

List emptyList= 新的数组列表<>;System.out.println(emptyList.stream().collect(Collectors.joining(,", [", ]")));

<代码>[]

无字符串

推荐答案

老实说,我会采用你目前的方法(测试空虚).

Honestly, I would go with your current approach (testing for emptiness).

但如果你真的想使用直接收集器,你可以使用 Collections.joiningStringJoiner 的 Javadoc 作为制作自定义收集器的指南:

But if you really wanted to use a straight collector, you could use the source code of Collections.joining and the Javadoc of StringJoiner as a guide to make a custom collector:

Collector.of(
    () -> new StringJoiner(",", "[", "]").setEmptyValue("No strings"),
    StringJoiner::add,
    StringJoiner::merge,
    StringJoiner::toString)

相关文章