Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaStringJoiner Class vs String.join() Method to Join String in Java with Examples

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: Without StringJoiner Class and without String.join() method

Approach :

  • In this program we will not use java 8 we will try to do it manually and try to understand for this simple operation of the concatenation of strings with delimiter how much bigger code/steps we needed to achieve our goal.
  • First, we will join three strings “DSA”, “FAANG”, “ALGO”, and the delimiter will be “gfg” for doing this we need to write delimiter every time before adding the next string.
  • Next, we will join elements of an ArrayList containing strings “DSA”,”FAANG”, “ALGO” and delimiter will be ” gfg ” and for doing this we needed to iterate over ArrayList and then add strings using a delimiter.
  • Note here for i=0 we directly assigned the string joined2 to the first element of ArrayList because if we didn’t put this condition then we will get the output like this ” gfg DSA gfg FAANG gfg ALGO” whereas the actual output did not have a delimiter before the first element of ArrayList “DSA gfg FAANG gfg ALGO”.
  • As from the code you can see how much code is written for doing this simple task for doing task now we will look for using StringJoiner class and String.join() method.

Java




// Java program for joining the strings before Java8
// by simple method using '+' to concatenate 
  
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
  
class GFG {
    public static void main(String[] args)
    {
        // Here we need to join strings "DSA","FAANG","ALGO"
        // and with delimiter " gfg "
        String joined = "DSA"
                        + " gfg "
                        + "FAANG"
                        + " gfg "
                        + "ALGO";
  
        // Here we created an ArrayList of strings
        // ArrayList contains "DSA","FAANG","ALGO"
        ArrayList<String> gfgstrings = new ArrayList<>(
            Arrays.asList("DSA", "FAANG", "ALGO"));
        
        String joined2 = "";
        
        // Now we will iterate over ArrayList
        for (int i = 0; i < gfgstrings.size(); i++) {
            
            // for i== 0 we do not want to add space before
            // first word thats why we checked for i=0
            if (i == 0) {
                joined2 = gfgstrings.get(i);
            }
  
            else {
                joined2
                    = joined2 + " gfg " + gfgstrings.get(i);
            }
        }
        
        // printing the first output
        System.out.println(joined);
        System.out.println("--------------------");
        
        // printing the second output
        System.out.println(joined2);
    }
}


Output

DSA gfg FAANG gfg ALGO
--------------------
DSA gfg FAANG gfg ALGO

StringJoiner Class :

StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. In simple words in the constructor of StringJoiner calls we can pass Three parameters delimiter, suffix, prefix. Prefix be added to the start of a String and suffix will be at the end. For adding the strings we will need to simply call the add() method on the StringJoiner class.

Syntax :

If we have suffix and prefix

StringJoiner joined=StringJoiner(delimiter,prefix,suffix)

joined.add(string1);
joined.add(string2);
joined.add(string3);

If we don’t have suffix and prefix

StringJoiner joined=StringJoiner(delimiter)

joined.add(string1);
joined.add(string2);
joined.add(string3);

Approach:

  • If you are adding a group of strings you need to create StringJoiner class Object and pass delimiter, prefix, suffix.
  • Here the delimiter is “gfg ” string and the prefix is “[” and suffix is “]”. Now we need to add strings in StringJoiner class using add() method.
  • Finally, we will convert the StringJoiner object to a String object using toString() method.
  • In case we have ArrayList of strings the delimiter is “gfg ” and prefix is “[” and suffix is “]” and we will iterate over the Arraylist and elements in StringJoiner and then convert into String object.
  • Finally, we will print the output.

Program of joining Strings using StringJoiner class :

Java




// Java program for joining the strings
// Using StringJoiner class
  
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringJoiner;
  
class GFG {
    public static void main(String[] args)
    {
        // Here we need to join strings "DSA","FAANG","ALGO"
        // and with delimiter " gfg "
        StringJoiner sj
            = new StringJoiner(" gfg ", "[", "]");
        
        sj.add("DSA");
        sj.add("FAANG");
        sj.add("ALGO");
        
        // Convert StringJoiner to String
        String joined = sj.toString();
  
        // Here we created an ArrayList of strings
        ArrayList<String> gfgstrings = new ArrayList<>(
            Arrays.asList("DSA", "FAANG", "ALGO"));
        
        // StringJoiner class having parameters
        // delimiter,prefix,suffix
        StringJoiner sj2
            = new StringJoiner(" gfg ", "[", "]");
        
        // Now we will iterate over ArrayList
        // and adding in string Joiner class
        for (String arl : gfgstrings) {
            sj2.add(arl);
        }
        
        // convert StringJoiner object to String
        String joined2 = sj2.toString();
  
        // printing the first output
        System.out.println(joined);
        System.out.println("--------------------");
        
        // printing the second output
        System.out.println(joined2);
    }
}


Output

[DSA gfg FAANG gfg ALGO]
--------------------
[DSA gfg FAANG gfg ALGO]

String.join():

The java.lang.string.join() method concatenates the given element with the delimiter and returns the concatenated string. Note that if an element is null, then null is added. The join() method was introduced in java string since JDK 1.8. String.join() method takes two parameters first is a delimiter and the second can be a list or array of elements or elements separated by ,(comma).

Syntax :

In the case of individual elements

String joined=String.join("delimiter","element1","element2,"element3"...);

In the case of List

String joined2=String.join("delimiter",listObject);

Return Type: It returns the string joined by using of delimiter

Example:

Approach:  Joining strings using String.join() method

  • In this example for the individual string, we need to pass the delimiter and strings in join() method. Here delimiter is ” gfg ” and strings are “DSA”, “FAANG”, “ALGO”.
  • String.join() will return the string joined using a delimiter.
  • For ArrayList, we need to simply pass the delimiter and list object in join method join(” gfg “,listObject) this will return the string joined using delimiter on each element of ArrayList.

Java




// Java program for joining the strings
// Using String.join() method
  
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringJoiner;
  
class GFG {
    public static void main(String[] args)
    {
        // Here we need to join strings "DSA","FAANG","ALGO"
        // and with delimiter " gfg "
  
        String joined
            = String.join(" gfg ", "DSA", "FAANG", "ALGO");
  
        // Here we created an ArrayList of strings
        ArrayList<String> gfgstrings = new ArrayList<>(
            Arrays.asList("DSA", "FAANG", "ALGO"));
        
        String joined2 = String.join(" gfg ", gfgstrings);
  
        // printing the first output
        System.out.println(joined);
        
        System.out.println("--------------------");
        
        // printing the second output
        System.out.println(joined2);
    }
}


Output

DSA gfg FAANG gfg ALGO
--------------------
DSA gfg FAANG gfg ALGO
RELATED ARTICLES

Most Popular

Recent Comments