Collectors Joining Delimited Stream
Concatenate stream elements with Collectors.joining, adding delimiters, prefixes, suffixes, and mapping each element to text in one terminal operation.
Code
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ReportLine {
public static void main(String[] args) {
List<String> hosts = List.of("web-1", "web-2", "db-1");
// 无参 joining:元素直接拼接,没有分隔符
String glued = hosts.stream().collect(Collectors.joining());
System.out.println(glued);
// 单参 joining:分隔符插在元素之间,首尾不出现
String csv = hosts.stream().collect(Collectors.joining(", "));
System.out.println(csv);
// 三参 joining:前缀、分隔符、后缀一次成型
String bracketed = hosts.stream().collect(Collectors.joining(", ", "[", "]"));
System.out.println(bracketed);
// 映射后拼接:先把元素转成文本再 join,避免中间集合
String upper = Stream.of("deploy", "verify")
.collect(Collectors.joining(" -> ", "steps: ", "!"));
System.out.println(upper);
}
}How it works
Collectors Joining Delimited Stream comes down to the class ReportLine and the function main.
The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: public static void main(String[] args)
Key statements
String bracketed = hosts.stream().collect(Collectors.joining(", ", "[", "]"));
String csv = hosts.stream().collect(Collectors.joining(", "));
String glued = hosts.stream().collect(Collectors.joining());
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- How do you run Collectors Joining Delimited Stream?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.