How to use String.join() method in Java?

Jan 27 2024
String.join() joins the given string elements with the specified delimiter by concatenating them with the delimiter and returns a new string. A collection of strings can also be joined by this method.

String.join() joins the given string elements with the specified delimiter by concatenating them with the delimiter and returns a new string. A collection of strings can also be joined by this method. If null is specified as a string element, it will also be joined as it is. The delimiter can not be null.

This method internally uses StringJoiner class which can also be used directly.

Signature

This is a static method and has 2 variants. Below are their signatures.

public static String join(CharSequence delimiter, CharSequence... elements)

public static String join(CharSequence delimiter, Iterable<? Extends CharSequence> elements)

Parameters

  • delimiter — delimiter to be used while joining strings.
  • elements — elements to be joined which must implement CharSequence interface. String class implements this interface.

The first variant takes in delimiter and n number of string elements and the other one takes in delimiter and a collection of strings.

NoteCharSequence is an interface and all it downstream classes can be used with this method.

Example

import java.util.ArrayList;

public class Demo {

  public static void main(String[] args) {
    System.out.println(String.join("-", "31", "12", "2020"));
    System.out.println(String.join("/", "31", "12", "2020"));

    ArrayList<String> cities = new ArrayList<>();
    cities.add("Texas");
    cities.add("Florida");
    cities.add("Arizona");

    System.out.println(String.join(",", cities));
    System.out.println(String.join(",", null, "aa", "bb", null));
  }
}

and below is the output.

31-12-2020
31/12/2020
Texas,Florida,Arizona
null,aa,bb,null