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)
这篇关于仅当流不是空后缀时,自定义收集器才在分隔符、后缀和前缀上加入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:仅当流不是空后缀时,自定义收集器才在分隔符、后缀和前缀上加入流


基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- Struts2 URL 无法访问 2022-01-01