Custom Collector to join stream on delimiter, suffix and prefix only if stream is not empty suffix(仅当流不是空后缀时,自定义收集器才在分隔符、后缀和前缀上加入流)
问题描述
我有一个字符串流:
流<字符串>流 = ...;
我想创建一个字符串使用
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 super String, ?, String> 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
<代码>[]代码>
无字符串
推荐答案
老实说,我会采用你目前的方法(测试空虚).
Honestly, I would go with your current approach (testing for emptiness).
但如果你真的想使用直接收集器,你可以使用 Collections.joining
和 StringJoiner
的 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)
这篇关于仅当流不是空后缀时,自定义收集器才在分隔符、后缀和前缀上加入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:仅当流不是空后缀时,自定义收集器才在分隔符、后缀和前缀上加入流


基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01