Adding a whitespace inside a List of strings

There are multiple way to Add a whitespace inside a List of strings. here we are using delimiter to add whitespace. A delimiter is a CharSequence that is used to separate words from each other.

String join() method :-

  • The String join() method returns a string joined with a given delimiter.
  • Here the String join() method, the space delimiter is copied for each element.
  • Space delimiter came inside list data and display result.

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

Collectors.joining() method :-

  • Collectors.joining(CharSequence delimiter) is a joining() method which takes delimiter as a type CharSequence parameter.
  • It returns a Collector that joins the input streams into a String.
  • Here we stream the list of data and add space delimiter(” “) from Collectors.joining() method.
  • Display the return of string result.

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

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

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


Output :-
from string.join method :- Delhi London Brazil Mumbai
collectors.joining method :- Delhi London Brazil Mumbai