(Translated by https://www.hiragana.jp/)
StringJoiner Class in Java - GeeksforGeeks
Open In App

StringJoiner Class in Java

Last Updated : 24 Jan, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

StringJoiner is a class in java.util package is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a given suffix. Though this can also be done with the help of the StringBuilder class to append delimiter after each string, StringJoiner provides an easy way to do that without much code to write. 

Constructors of StringJoiner Class

1. StringJoiner(CharSequence delimiter): It constructs a StringJoiner with no characters, no prefix or suffix, and a copy of the supplied delimiter. 

Syntax: 

public StringJoiner(CharSequence delimiter)

Parameters: The sequence of characters to be used between each element added to the StringJoiner value

Exception Thrown: NullPointerException if the delimiter is null

2. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): It constructs a StringJoiner with no characters using copies of the supplied prefix, delimiter, and suffix. If no characters are added to the StringJoiner and methods accessing the string value are invoked, it will return the prefix + suffix (or properties thereof) in the result unless setEmptyValue has first been called. 

Syntax: 

public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

Parameters: 

  • The sequence of characters to be used between each element added to the StringJoiner value
  • The sequence of characters to be used at the beginning
  • The sequence of characters to be used at the end

Exception Thrown: NullPointerException if prefix, delimiter, or suffix is null.

Methods of StringJoiner Class

Method  Action Performed
add() Adds a copy of the given CharSequence value as the next element of the StringJoiner value. If newElement is null, then “null” is added. 
length()  Returns the length of the String representation of this StringJoiner. 
merge() Adds the contents of the given StringJoiner without prefix and suffix as the next element if it is non-empty. If the given StringJoiner is empty, the call has no effect. Suppose the other StringJoiner is using a different delimiter. In that case, elements from the other StringJoiner are concatenated with that delimiter, and the result is appended to this StringJoiner as a single element. 
toString() Returns the String object of this StringJoiner
setEmptyValue() Sets the string to be used when determining the string representation of this StringJoiner, and no elements have been added yet; that is when it is empty

 Example:

Java




// Java program to Demonstrate Methods
// of StringJoiner class
 
// Importing required classes
import java.util.ArrayList;
import java.util.StringJoiner;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty ArrayList of string type
        ArrayList<String> al = new ArrayList<>();
 
        // Adding elements to above List
        al.add("Ram");
        al.add("Shyam");
        al.add("Alice");
        al.add("Bob");
 
        // Creating object of class inside main()
        StringJoiner sj1 = new StringJoiner(",");
 
        // Using setEmptyValue() method
        sj1.setEmptyValue("sj1 is empty");
        System.out.println(sj1);
 
        // Using add() method
        sj1.add(al.get(0)).add(al.get(1));
        System.out.println(sj1);
 
        // Using length() method
        System.out.println("Length of sj1 : "
                           + sj1.length());
 
        StringJoiner sj2 = new StringJoiner(":");
        sj2.add(al.get(2)).add(al.get(3));
 
        // Using merge() method
        sj1.merge(sj2);
 
        // Using toString() method
        System.out.println(sj1.toString());
 
        System.out.println("Length of new sj1 : "
                           + sj1.length());
    }
}


Output

sj1 is empty
Ram,Shyam
Length of sj1 : 9
Ram,Shyam,Alice:Bob
Length of new sj1 : 19

 



Previous Article
Next Article

Similar Reads

StringJoiner Class vs String.join() Method to Join String in Java with Examples
Prior to Java 8 when we need to concatenate a group of strings we need to write that code manually in addition to this we needed to repeatedly use delimiter and sometimes it leads to several mistakes but after Java 8 we can concatenate the strings using StringJoiner class and String.join() method then we can easily achieve our goal. Example: Withou
6 min read
StringJoiner add() method in Java
The add(CharSequence newElement) of StringJoiner adds a copy of the given CharSequence value as the next element of the StringJoiner value. If newElement is null, then "null" is added.Syntax: public StringJoiner add(CharSequence newElement) Parameters: This method takes a mandatory parameter newElement which is the element to be added.Returns: This
1 min read
StringJoiner length() method in Java
The length() of StringJoiner is used to find out the length of the StringJoiner in characters. It returns the length of the String representation of this StringJoiner. Note that if no add methods have been called, then the length of the String representation (either prefix + suffix or emptyValue) will be returned. The value should be equivalent to
2 min read
StringJoiner merge() method in Java
The merge(StringJoiner other) of StringJoiner adds the contents of the given StringJoiner without prefix and suffix as the next element if it is non-empty. If the given StringJoiner is empty, the call has no effect.Syntax: public StringJoiner merge(StringJoiner other) Parameters: This method accepts a mandatory parameter other which is the StringJo
3 min read
StringJoiner toString() method in Java
The toString() of StringJoiner is used to convert StringJoiner to String. It returns the current value, consisting of the prefix, the values added so far separated by the delimiter, and the suffix, unless no elements have been added in which case, the prefix + suffix or the emptyValue characters are returnedSyntax: public String toString() Returns:
2 min read
StringJoiner setEmptyValue() method in Java
The setEmptyValue(CharSequence emptyValue) of StringJoiner sets the sequence of characters to be used when determining the string representation of this StringJoiner and no elements have been added yet, that is, when it is empty. A copy of the emptyValue parameter is made for this purpose. Note that once an add method has been called, the StringJoi
2 min read
When to use StringJoiner over StringBuilder?
Prerequisite: StringJoinerStringJoiner is very useful, when you need to join Strings in a Stream. Task : Suppose we want the string "[George:Sally:Fred]", where we have given a string array that contains "George", "Sally" and "Fred".StringJoiner provide add(String str) method to concatenate the strings based on supplied delimiter,prefix and suffix
2 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Implement Pair Class with Unit Class in Java using JavaTuples
To implement a Pair class with a Unit class in Java using JavaTuples, you can use the Pair class provided by the library and create a new Unit class that extends the Unit class provided by the library. Here is an example implementation: Here is an example Java code that uses the MyPair class with MyUnit and displays the output: Java Code import org
4 min read
Implement Triplet Class with Pair Class in Java using JavaTuples
Following are the ways to implement Triplet Class with Pair Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Pair Pair&lt;Integer, String&gt; pair = new Pair&lt;Integer, String&gt;( Integer.valueOf(1), &quot;GeeksforGeeks&quot;); // Print the Pair System.out.printl
2 min read
Implement Quintet Class with Quartet Class in Java using JavaTuples
Following are the ways to implement Quintet Class with Quartet Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Quartet Quartet&lt;String, String, String, String&gt; quartet = new Quartet&lt;String, String, String, String&gt;( &quot;Quartet&quot;, &quot;Triplet
4 min read
Implement Quartet Class with Triplet Class in Java using JavaTuples
Following are the ways to implement Quartet Class with Triplet Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Triplet Triplet&lt;String, String, String&gt; triplet = new Triplet&lt;String, String, String&gt;( &quot;Triplet 1&quot;, &quot;1&quot;, &quot;GeeksforGe
3 min read
Implement Octet Class from Septet Class in Java using JavaTuples
Prerequisite: Octet Class, Septet Class Below are the methods to implement a Octet Class using Septet Class in Java: Using direct values // Java program to illustrate // implementing Octet Class // from Septet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create Sep
6 min read
Implement Ennead Class from Octet Class in Java using JavaTuples
Prerequisite: Ennead Class, Octet Class Below are the methods to implement a Ennead Class using Octet Class in Java: Using direct values // Java program to illustrate // implementing Ennead Class // from Octet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create Oct
7 min read
Implement Sextet Class from Quintet Class in Java using JavaTuples
Prerequisite: Sextet Class, Quintet Class Below are the methods to implement a Sextet Class using Quintet Class in Java: Using direct values // Java program to illustrate // implementing Sextet Class // from Quintet Class using // direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // crea
5 min read
Implement Septet Class from Sextet Class in Java using JavaTuples
Prerequisite: Septet Class, Sextet Class Below are the methods to implement a Septet Class using Sextet Class in Java: Using direct values // Java program to illustrate // implementing Septet Class // from Sextet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create
6 min read
Implement Decade Class from Ennead Class in Java using JavaTuples
Prerequisite: Decade Class, Ennead Class Below are the methods to implement a Decade Class using Ennead Class in Java: Using direct values // Java program to illustrate // implementing Decade Class // from Ennead Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create
8 min read
Difference between Abstract Class and Concrete Class in Java
Abstract Class: An abstract class is a type of class in Java that is declared by the abstract keyword. An abstract class cannot be instantiated directly, i.e. the object of such class cannot be created directly using the new keyword. An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along wit
5 min read
Java - Inner Class vs Sub Class
Inner Class In Java, one can define a new class inside any other class. Such classes are known as Inner class. It is a non-static class, hence, it cannot define any static members in itself. Every instance has access to instance members of containing class. It is of three types: Nested Inner ClassMethod Local Inner ClassAnonymous Inner Class Genera
3 min read
Java I/O Operation - Wrapper Class vs Primitive Class Variables
It is better to use the Primitive Class variable for the I/O operation unless there is a necessity of using the Wrapper Class. In this article, we can discuss briefly both wrapper class and primitive data type. A primitive data type focuses on variable values, without any additional methods.The Default value of Primitive class variables are given b
3 min read
Using predefined class name as Class or Variable name in Java
In Java, you can use any valid identifier as a class or variable name. However, it is not recommended to use a predefined class name as a class or variable name in Java. The reason is that when you use a predefined class name as a class or variable name, you can potentially create confusion and make your code harder to read and understand. It may a
5 min read
Why BufferedReader class takes less time for I/O operation than Scanner class in java
In Java, both BufferReader and Scanner classes can be used for the reading inputs, but they differ in the performance due to their underlying implementations. The BufferReader class can be generally faster than the Scanner class because of the way it handles the input and parsing. This article will guide these difference, provide the detailed expla
3 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Practice Tags :