Flat Preloader Icon

Java String Joiner

StringJoiner is a class introduced in Java 8 to help with joining strings, especially when you have a collection of strings or other objects that you want to concatenate with a delimiter. It provides a way to build a string by adding elements with a specified delimiter and optionally with a prefix and suffix.
Basic Usage:
				
					StringJoiner joiner = new StringJoiner(", ");
// Delimiter and optional prefix/suffix
joiner.add("Apple");
joiner.add("Banana");
joiner.add("Cherry");

String result = joiner.toString();
System.out.println(result); 
// Output: Apple, Banana, Cherry

				
			
With Prefix and Suffix: You can specify a prefix and a suffix for the joined string:
				
					StringJoiner joiner = new StringJoiner(", ", "[", "]");
joiner.add("One");
joiner.add("Two");
joiner.add("Three");

String result = joiner.toString();
System.out.println(result); // Output: [One, Two, Three]

				
			
Merging StringJoiners: You can merge the contents of one StringJoiner into another:
				
					StringJoiner fruits = new StringJoiner(", ");
fruits.add("Apple");
fruits.add("Banana");

StringJoiner moreFruits = new StringJoiner(", ");
moreFruits.add("Cherry");
moreFruits.add("Date");

fruits.merge(moreFruits); 
// Merges moreFruits into fruits

String result = fruits.toString();
System.out.println(result); 
// Output: Apple, Banana, Cherry, Date

				
			
Using Collectors.joining(): The Collectors.joining() method in the Java Stream API uses StringJoiner under the hood and provides a concise way to join elements in a stream:
				
					List<String> fruits = 
Arrays.asList("Apple", "Banana", "Cherry");
String result = 
fruits.stream().collect(Collectors.joining(", "));
System.out.println(result); 
// Output: Apple, Banana, Cherry

				
			
StringJoiner is particularly useful when you need to concatenate elements from collections or arrays into a single string with a specified delimiter, prefix, and suffix. It makes your code more readable and can help eliminate the need for explicit loops and conditional checks.

Share on: