StringJoiner is a utility class in Java that makes it easy to concatenate strings with a delimiter, optionally including a prefix and/or a suffix. This can be especially useful when trying to generate sequences like comma-separated values.
Introduced in Java 8, StringJoiner is part of the java.util package.
StringJoinerYou can create a StringJoiner by specifying a delimiter:
StringJoiner joiner = new StringJoiner(", "); joiner.add("Alice"); joiner.add("Bob"); joiner.add("Charlie"); System.out.println(joiner.toString()); // Outputs: Alice, Bob, Charlie
StringJoiner allows you to specify an optional prefix and suffix:
StringJoiner joiner = new StringJoiner(", ", "{", "}"); joiner.add("Alice"); joiner.add("Bob"); joiner.add("Charlie"); System.out.println(joiner.toString()); // Outputs: {Alice, Bob, Charlie} StringJoiner InstancesYou can merge two StringJoiner instances. This comes in handy when you have multiple sections of data to concatenate:
StringJoiner joiner1 = new StringJoiner(", "); joiner1.add("Alice"); joiner1.add("Bob"); StringJoiner joiner2 = new StringJoiner(", "); joiner2.add("Charlie"); joiner2.add("David"); joiner1.merge(joiner2); System.out.println(joiner1.toString()); // Outputs: Alice, Bob, Charlie, David Note: The prefix and suffix of the second StringJoiner (if specified) are ignored when merging.
StringJoiner pairs well with Java Streams. You can use the Collectors.joining() method to collect a stream into a string, which internally uses StringJoiner:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); String result = names.stream().collect(Collectors.joining(", ")); System.out.println(result); // Outputs: Alice, Bob, Charlie When the StringJoiner has no values and it's printed, by default, it will just show the prefix and suffix. You can set a default value to display when it's empty:
StringJoiner joiner = new StringJoiner(", "); joiner.setEmptyValue("No names available."); System.out.println(joiner.toString()); // Outputs: No names available. StringJoiner can be particularly useful when constructing strings for:
StringJoiner offers an elegant way to handle string concatenation with delimiters in Java. Its compatibility with streams, prefix/suffix handling, and merging capabilities make it a powerful tool in a developer's toolkit. Always consider using StringJoiner when faced with constructing complex string sequences.
tinymce mysql-error-1292 applicationcontext sql-drop css-loader linq-to-objects indicator swap flutter-test popen