仅当流不为空后缀时,Custom Collector才能在定界符,后缀和前缀上加入流 [英] Custom Collector to join stream on delimiter, suffix and prefix only if stream is not empty suffix

查看:71
本文介绍了仅当流不为空后缀时,Custom Collector才能在定界符,后缀和前缀上加入流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一串字符串:

Stream<String> stream = ...;

我想使用创建一个字符串

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< T,A,R>

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到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<String> = new ArrayList<>; System.out.println(emptyList.stream().collect(Collectors.joining(",", "[", "]")));

[]

No Strings

推荐答案

老实说,我会采用您当前的方法(测试是否为空).

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

但是,如果您真的想使用直接收集器,则可以使用

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)

这篇关于仅当流不为空后缀时,Custom Collector才能在定界符,后缀和前缀上加入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆