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

Viewed 2130

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

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

Output

[]

Output I would like

No Strings

1 Answers

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)
Related