I have a stream of strings:
Stream<String> stream = ...;
I want to construct a string which concatenates these items with ,
as a separator. I do this as following:
stream.collect(Collectors.joining(","));
Now I want add a prefix [
and a suffix ]
to this output only if there were multiple items. For example:
a
[a,b]
[a,b,c]
Can this be done without first materializing the Stream<String>
to a List<String>
and then checking on List.size() == 1
? In code:
public String format(Stream<String> stream) {
List<String> list = stream.collect(Collectors.toList());
if (list.size() == 1) {
return list.get(0);
}
return "[" + list.stream().collect(Collectors.joining(",")) + "]";
}
It feels odd to first convert the stream to a list and then again to a stream to be able to apply the Collectors.joining(",")
. I think it's suboptimal to loop through the whole stream (which is done during a Collectors.toList()
) only to discover if there is one or more item(s) present.
I could implement my own Collector<String, String>
which counts the number of given items and use that count afterwards. But I am wondering if there is a directer way.
This question intentionally ignores there case when the stream is empty.