StringJoiner add() method in Java 8


The add() method of the StringJoiner class is used in Java 8 to add a copy of the given CharSequence value as the next element of the StringJoiner value. If the new element ele is null, then the value null gets added.

The syntax is as follows −

public StringJoiner add(CharSequence ele)

Here, the parameter ele is the element to be added, whereas, CharSequence is a readable sequence of char values.

To work with the StringJoiner in Java 8, import the following package −

import java.util.StringJoiner;

We will first create a StringJoiner and set the delimeter −

StringJoiner strJoin = new StringJoiner(",")

Use the add() method to add elements to the StringJoiner −

strJoin.add("ABC");
strJoin.add("DEF");
strJoin.add("GHI");
strJoin.add("JKL");

The following is an example to implement StringJoiner add() method in Java −

Example

 Live Demo

import java.util.StringJoiner;
public class Demo {
   public static void main(String[] args) {
      StringJoiner strJoin = new StringJoiner(",");
      strJoin.add("ABC");
      strJoin.add("DEF");
      strJoin.add("GHI");
      strJoin.add("JKL");
      strJoin.add("MNO");
      strJoin.add("PQR");
      System.out.println(strJoin.toString());
   }
}

Output

ABC,DEF,GHI,JKL,MNO,PQR

Let us now see what will happen when we will insert null values using the add() method −

Example

 Live Demo

import java.util.StringJoiner;
public class Demo {
   public static void main(String[] args) {
      StringJoiner strJoin = new StringJoiner(",");
      strJoin.add(null);
      strJoin.add(null);
      strJoin.add("GHI");
      strJoin.add(null);
      strJoin.add("MNO");
      strJoin.add(null);
      System.out.println(strJoin.toString());
   }
}

The output is as follows displaying the null values as well −

Output

null,null,GHI,null,MNO,null

Updated on: 30-Jul-2019

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements