Join or combine two / multiple Strings using StringJoiner in java8 (example)

  • Given two or more strings in java, we would like to concatenate or combine multiple strings.
  • Java 8 has provided a new class to join Strings.
    • We will use StringJoiner class to concat strings.
  • We will demonstrate, how can we join strings using traditional approach and StringJoiner class.
    1. Combine or concat String without StringJoiner class (using StringBuilder class)
    2. Combine Strings using StringJoiner class in Java8

1. StringJoiner class have following constructors.

public StringJoiner(CharSequence delimiter)
public StringJoiner(CharSequence delimiter,
                    CharSequence prefix,
                    CharSequence suffix)
  1. Constructor taking delimiter only.
    • [Example 1 in below code]
  2. Constructor taking delimiter, prefix and suffix
    • [Example 2 and Example 3 in below code]

2. Join or combine multiple Strings – StringBuilder /StringJoiner (java8)

package org.learn;

import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

public class StringJoin {

	public static void main(String[] args) {
		//Traditional approach.. Without Java 8 class
		StringBuilder builder = new StringBuilder();
		builder.append("Example");
		builder.append(",");
		builder.append("Of");
		builder.append(",");
		builder.append("String");
		builder.append(",");
		builder.append("Joiner");
		System.out.println("Traditional approach : "+builder.toString());
		
		//Java 8 -> New feature
		//Example 1
		StringJoiner joiner = new StringJoiner(",");
		joiner.add("Example");
		joiner.add("Of");
		joiner.add("String");
		joiner.add("Joiner");
		//Output -> Example,Of,String,Joiner
		System.out.println("Example 1 : "+joiner.toString());
		
		//Example 2
		joiner = new StringJoiner(",","[","]");
		joiner.add("Example");
		joiner.add("Of");
		joiner.add("String");
		joiner.add("Joiner");
		//Output -> [Example,Of,String,Joiner]
		System.out.println("Example 2 : "+joiner.toString());
		
		//Example 3
		List<String> stringList = Arrays.asList("Example","Of","String","Joiner");
		String example3 = stringList.stream()		     
		     .collect(Collectors.joining(",","[","]"));
		//Output -> [Example,Of,String,Joiner]
		System.out.println("Example 3 : "+example3);
	}
}

O/P: Concatenate multiple Strings – StringBuilder /StringJoiner (java8)

Traditional approach : Example,Of,String,Joiner
Example 1 : Example,Of,String,Joiner
Example 2 : [Example,Of,String,Joiner]
Example 3 : [Example,Of,String,Joiner]
Scroll to Top