How to join string in Java

In this post, we are going to join two or more string into a single string using Java code. We are joining string into a single string that is separated by a delimiter. For example, we have two strings "India" and "New Delhi" then while joining we use "-" delimiter so the resulted string will be "India-NewDelhi".

To join multiple strings, we are using join() method of String class. The join() method has two overloaded versions in which one takes a string as an argument and second take iterable (list, set) as an argument and returns a single string after joining.

Time for an example:

Let's create an example to get a string after joining multiple strings. Here, we are using the join() method that takes delimiter as a first argument and others are string arguments.

public class Main {
	public static void main(String[] args){
		String str1 = "Mango";
		String str2 = "Orange";
		String str3 = "Apple";
		// Join all strings
		String str = String.join("-", str1, str2, str3);
		System.out.println(str);
		System.out.println(str.getClass().getName());
	}
}


Mango-Orange-Apple
java.lang.String

Example:

Let's create another example to join string. Here, we are using join() method to join list of string into a single string. We used hyphen (-) symbol to join strings.

import java.util.Arrays;
import java.util.List;

public class Main {
	public static void main(String[] args){
		List <String> list = Arrays.asList("Mango","Orange","Apple");
		// Join all strings
		String str = String.join("-", list);
		System.out.println(str);
		System.out.println(str.getClass().getName());
	}
}


Mango-Orange-Apple
java.lang.String

Example: Java 8

If you are using Java 8 or higher version, then we can use stream() method of the list and then collect all the string into a single using joining() method of Collectors.

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

public class Main {
	public static void main(String[] args){
		List <String> list = Arrays.asList("Mango","Orange","Apple");
		// Join all strings
		String str = list.stream().collect(Collectors.joining("-"));
		System.out.println(str);
		System.out.println(str.getClass().getName());
	}
}


Mango-Orange-Apple
java.lang.String