How to Join a List of Strings with a Space in Java 8

There are multiple ways to join a list of strings with a space in Java 8. In this example, we use a space delimiter to separate the elements of a list.
A delimiter is a character sequence used to separate values in a string.

String join() method :-

The String.join() method is used to join multiple strings with a specified delimiter.

  • It returns a single string by joining all elements.
  • The delimiter is inserted between each element.

Syntax :- public static String join(CharSequence delimiter, CharSequence… elements)

Collectors.joining() method :-

The Collectors.joining() method is part of Java Streams API .

  • Returns a single concatenated string .
  • Display the return of string result.

Syntax :-   public static Collector<CharSequence, ?, String> joining(CharSequence delimiter)

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

public class AddSpaceData {
	public static void main(String[] args) {
		
		List<String> city = Arrays.asList("Delhi", "London", "Brazil", "Mumbai");
        // Using string.join method
		String str = String.join(" ", city);
		System.out.println("Using string.join() method :- "+str);
        
		// Using collectors.joining method
		String p = city.stream().collect(Collectors.joining(" "));
		System.out.println("Using collectors.joining() method :- "+p);

	}
}
				
			

Output :-
Using string.join() method :- Delhi London Brazil Mumbai
Using collectors.joining() method :- Delhi London Brazil Mumbai