- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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
- Related Articles
- StringJoiner setEmptyValue() method in Java 8
- StringJoiner toString() method in Java 8
- StringJoiner merge() method in Java 8
- StringJoiner length() method in Java 8
- What is StringJoiner class in Java 8?
- StringJoiner Class vs String.join() Method to Join String in Java
- LongStream.Builder add() method in Java
- DoubleStream.Builder add() method in Java
- ArrayBlockingQueue add() method in Java
- IntStream.Builder add() method in Java
- Collectors.joining() method in Java 8
- The add() method in Java Stream.Builder
- Collectors toSet() method in Java 8
- Collectors averagingLong () method in Java 8
- Collectors averagingDouble() method in Java 8
