Custom Collector to join stream on delimiter, suffix and prefix only if stream is not empty suffix

霸气de小男生 提交于 2020-03-05 05:40:15

问题


I have a stream of strings:

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.

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

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

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(',', '[', ']'));`

This is what I would like to happen

List emptyList = new ArrayList<String>; System.out.println(emptyList.steam().collect(Collectors.joining(',', '[', ']')));

Output

[,]

Output I would like

No Strings


回答1:


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)



回答2:


I would also recommend using the if statement you already have. To generate the String after that you can also use String.join():

List<String> list = stream.collect(Collectors.toList());
if (list.isEmpty()) {
    return "No Strings";
}
return "[" + String.join(",", list) + "]";

If you do not want the if you also can use an Optional to prevent that:

return Optional.of(stream.collect(Collectors.toList()))
        .filter(l -> !l.isEmpty())
        .map(l -> "[" + String.join(",", l) + "]")
        .orElse("No Strings");

But I don't think this is more readable.



来源:https://stackoverflow.com/questions/56560842/custom-collector-to-join-stream-on-delimiter-suffix-and-prefix-only-if-stream-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!