Common Use Cases: CSV, JSON, and Formatted Output
What you'll learn: How to leverage joining() to generate practical formatted outputs like CSV files, JSON arrays, SQL queries, and human-readable lists.
Real-World Formatting with joining()
Now that you understand joining() with delimiters, prefixes, and suffixes, let's apply it to solve common formatting challenges. The joining() collector shines when you need to convert stream data into standardized text formats.
CSV Output
Generate comma-separated values for export files:
List<String> columns = List.of("Alice", "Bob", "Charlie");
String csvLine = columns.stream()
.collect(Collectors.joining(","));
// Result: "Alice,Bob,Charlie"
JSON Array Format
Create JSON-compatible arrays with brackets and commas:
List<Integer> ids = List.of(101, 102, 103);
String jsonArray = ids.stream()
.map(String::valueOf)
.collect(Collectors.joining(", ", "[", "]"));
// Result: "[101, 102, 103]"
SQL IN Clauses
Build dynamic SQL queries with proper quoting:
List<String> usernames = List.of("alice", "bob", "charlie");
String sqlIn = usernames.stream()
.collect(Collectors.joining("', '", "('", "')"));
// Result: "('alice', 'bob', 'charlie')"
// Use in: SELECT * FROM users WHERE name IN ('alice', 'bob', 'charlie')
Human-Readable Lists
Format data for display to users:
List<String> items = List.of("apples", "oranges", "bananas");
String shoppingList = items.stream()
.collect(Collectors.joining(", ", "Shopping list: ", "."));
// Result: "Shopping list: apples, oranges, bananas."
Why This Matters
These patterns eliminate manual string concatenation loops, reduce bugs from missing delimiters or quotes, and make your code declarative and readable. The same joining() method adapts to multiple output formats simply by changing parameters.
Key Takeaway: Use joining() with appropriate delimiters and affixes to generate CSV lines, JSON arrays, SQL clauses, and formatted text—turning streams into production-ready output strings in one clean operation.