Video in progress
How do you join strings with Collectors.joining()?
joining() gathers the CharSequences in a stream into one string. You can also give a delimiter, a prefix and a suffix: joining(", ", "[", "]").
📖 Answer
List<String> tags = List.of("java", "spring", "sql");
tags.stream().collect(Collectors.joining()); // javaspringsql
tags.stream().collect(Collectors.joining(", ")); // java, spring, sql
tags.stream().collect(Collectors.joining(", ", "[", "]")); // [java, spring, sql]
If the element isn't a String, map it first:
String ids = users.stream()
.map(u -> String.valueOf(u.id()))
.collect(Collectors.joining(",")); // "12,15,40"
On an empty stream joining(", ", "[", "]") returns "[]": the prefix and suffix are added anyway.
It uses a StringBuilder inside, so it is far more economical than doing += in a loop.
For the simple case without a stream there's also String.join(", ", tags). If you don't need a filter or map, that's enough.
One warning: building an SQL query this way ("WHERE id IN (" + ids + ")") opens the door to SQL injection. Use parameters.
Sign up to mark studied questions and save your progress.