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