joining
- Java course
- Advanced
- Lesson 3/82
- 5 min
Learn string joining with Collectors.joining.
Joining strings: joining
Collectors.joining merges the strings in a stream into a single string. Its simplest form takes no delimiter and just concatenates the strings. The delimiter version inserts a separator between elements.
Example: names.stream().collect(Collectors.joining(", ")). This call returns a single string such as "Alex, Mia, Sam". The delimiter is placed only between elements, never at the start or end. The result is always a String.
joining with prefix and suffix
The three-argument joining overload takes a delimiter, a prefix and a suffix. This is handy for turning a list into a one-line text snippet.
Example: Collectors.joining(", ", "[", "]"). This call returns a string such as "[Alex, Mia, Sam]". The delimiter sits between elements, the prefix at the front and the suffix at the end. For an empty stream only the prefix and suffix are joined; the delimiter is never used.
Practice Join names with a comma
Create a list of three names. Join the stream with Collectors.joining(", ") and print the result with System.out.println. The output must be a single line.
Starter code
import java.util.List;
import java.util.stream.Collectors;
// Join names with a comma
// Use Collectors.joining
// Print the resultSample solution
import java.util.List;
import java.util.stream.Collectors;
public class JoinNames {
public static void main(String[] args) {
List<String> names = List.of("Alex", "Mia", "Sam");
String result = names.stream().collect(Collectors.joining(", "));
System.out.println(result);
}
}Expected output
Alex, Mia, Sam
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does names.stream().collect(Collectors.joining(", ")) return?
- String Correct answer
- Map<String, String>
- List<String>
- Optional<String>
Explanation: joining always returns a String.
2 Complete the joining call
String result = names.stream()
.collect(Collectors.joining(____));
String result = names.stream()
.collect(Collectors.joining(", "));
Explanation: A comma and a space is the right delimiter.
3 Match the joining overloads
| Term | Meaning |
|---|---|
joining() |
Concatenates directly |
joining(delim) |
Separates with delimiter |
joining(delim, pre, suf) |
Adds prefix and suffix |