joining() vs String.join() and Manual Concatenation
What you'll learn: You'll understand when to use Collectors.joining() versus String.join() and why joining() shines in stream pipelines.
The Core Difference
Both Collectors.joining() and String.join() concatenate strings with delimiters, but they target different scenarios. String.join() works with collections that already exist in memory, while Collectors.joining() is designed specifically as a terminal operation for streams.
String.join() for Collections
When you have a ready-made collection and want to join its elements:
List<String> cities = List.of("Paris", "London", "Berlin");
String result = String.join(", ", cities);
// result: "Paris, London, Berlin"
This is direct and efficient for existing collections.
Collectors.joining() for Stream Pipelines
When you're transforming data in a stream pipeline, joining() fits naturally:
List<String> cities = List.of("Paris", "London", "Berlin");
String result = cities.stream()
.filter(city -> city.length() > 5)
.map(String::toUpperCase)
.collect(Collectors.joining(", "));
// result: "LONDON, BERLIN"
Why joining() is preferred for streams: It allows you to continue the functional chain without breaking into intermediate collections. You transform, filter, and collect in one fluent expression.
Manual Concatenation
Using loops with + or StringBuilder is error-prone and verbose:
StringBuilder sb = new StringBuilder();
for (String city : cities) {
sb.append(city).append(", ");
}
// Must manually remove trailing delimiter!
Both joining() and String.join() handle delimiters correctly without extra logic.
Key Takeaway: Use Collectors.joining() when collecting from a stream pipeline; use String.join() for simple concatenation of existing collections. Both beat manual concatenation by handling delimiters cleanly and efficiently.