The 30 second answer
I use Collectors.joining with a delimiter, and the three-argument form when they want a prefix and suffix like square brackets. It only accepts CharSequence elements, so numbers need map String::valueOf first. An empty stream still gives the prefix plus the suffix, and for a list that is already strings String.join is shorter.
var names = List.of("Ann", "Bob", "Cid");
String csv = names.stream().collect(Collectors.joining(", "));
// Ann, Bob, Cid
String bracketed = names.stream().collect(Collectors.joining(", ", "[", "]"));
// [Ann, Bob, Cid]
String fromInts = IntStream.rangeClosed(1, 3)
.mapToObj(String::valueOf)
.collect(Collectors.joining("-"));
// 1-2-3
String same = String.join(", ", names);Order: the Javadoc says joining concatenates in encounter order, so the result follows the list order.
Edge cases: an empty stream with the three-argument form returns "[]", the prefix plus the suffix. If an empty input should print something else, use StringJoiner with setEmptyValue("none"). A null element does not throw: when I ran it, the element came out as the text null, the same behavior StringJoiner.add documents. [Impl] Filter nulls first if that output is wrong for the caller.
Complexity: O(total length of the output) time and space. It uses one builder, so it avoids the repeated copying of + inside a loop.
What interviewers listen for: using joining instead of reduce with string concatenation, knowing it needs CharSequence, and covering the empty case.
Sources (3)
- Collectors.joiningdocs.oracle.com
- StringJoiner (setEmptyValue, add with null)docs.oracle.com
- String.joindocs.oracle.com