Core Java

Java 8 StringJoiner Example

Hello readers, in this tutorial, we will learn about the Java8 Stream’s API StringJoiner feature and we will explore its different characteristics.

1. Introduction

These days in the programming universe joining multiple strings are a common task among the developers. In the ancient Java world, there was no direct way to join the multiple strings. Java8 has introduced a final class namely StringJoiner to join the different strings. This class is defined in the java.util package and can be used to concatenate multiple random strings, a list of strings or an array of strings in Java.

StringJoiner class creates the sequence of characters separated by a delimiter. Developers can create the strings by passing delimiters like comma, colon, pipe, hyphen etc. This class also allows developers to specify a prefix and a suffix while joining two or more strings.

1.1 StringJoiner Constructors

In order to instantiate the StringJoiner class, Java8 provides two different types of constructors.

  • public StringJoiner(CharSequence delimiter): This creates the StringJoiner with no characters or prefix or suffix in it but with the supplied “delimiter”. If the delimiter is null, it throws the NullPointerException exception
  • public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): This creates a StringJoiner with a separator as a “delimiter”, prefix “p”, and suffix “s” for the resultant output

1.2 StringJoiner Methods

The table below describes the different methods provided by the StringJoiner class.

MethodDescription
public StringJoiner add(CharSequence newElement)This method adds the content of the CharSequence as the next element of the StringJoiner.
public StringJoiner merge(StringJoiner other)If the StringJoiner is non-empty, this method adds the content of the prefix and suffix as the next element to the StringJoiner. In case if the given StringJoiner is empty, the call has no effect.
public int length()This method returns the length of the String representation of the given StringJoiner.
public StringJoiner setEmptyValue(CharSequence emptyValue)This method is used if developers want to return any specific string if there are no strings added to the StringJoiner class. This method is called by passing a string value as an input argument.

Now, open up the Eclipse Ide and we will go over the StringJoiner and Collectors.joining() utilities in Java8 programming.

2. Java8 StringJoiner Example

2.1 Tools Used

We are using Eclipse Oxygen, JDK 1.8 and Maven.

2.2 Project Structure

Firstly, let’s review the final project structure if you’re confused about where you should create the corresponding files or folder later!

Fig. 1: Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will show on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 3: Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

1
2
3
4
5
6
7
    <modelVersion>4.0.0</modelVersion>
    <groupId>Java8Stringjoiner</groupId>
    <artifactId>Java8Stringjoiner</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
</project>

Developers can start adding the dependencies that they want. Let’s start building the application!

3. Application Building

Below are the steps involved in explaining this tutorial.

3.1 Java Class Implementation

Let’s create the required Java files. Right-click on the src/main/java folder, New -> Package.

Fig. 5: Java Package Creation
Fig. 5: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.java.

Fig. 6: Java Package Name (com.jcg.java)
Fig. 6: Java Package Name (com.jcg.java)

Once the package is created in the application, we will need to create the implementation class to show the StringJoiner usage. Right-click on the newly created package: New -> Class.

Fig. 7: Java Class Creation
Fig. 7: Java Class Creation

A new pop window will open and enter the file name as: StringjoinerDemo. The implementation class will be created inside the package: com.jcg.java.

Fig. 8: Java Class (StringjoinerDemo.java)
Fig. 8: Java Class (StringjoinerDemo.java)

3.1.1 Example of StringJoiner

Here is the complete Java program to show the concatenation of multiple strings using the StringJoiner in Java8 programming.

StringjoinerDemo.java

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package com.jcg.java;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
 
/* 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.
 *
 * @author Batra, Yatin
 */
public class StringjoinerDemo {
 
    public static void main(String[] args) {
 
        // Method #1 - Simple Delimiter Join
        joinDelimiter();
 
        System.out.println();
 
        // Method #2 - Join using Prefix and Suffix
        joinerWithPrefixSuffix();
 
        System.out.println();
 
        // Method #3 - Join using ListJoiner
        listJoiner();
 
        System.out.println();
 
        // Method #4 - Collection Joiner
        collectorJoiner();
 
        System.out.println();
 
        // Method #5 - Merging two StringJoiner objects
        mergeJoiner();
    }
 
    // Method #1
    public static void joinDelimiter() {
 
        // Passing The Delimiter
        StringJoiner myString = new StringJoiner("-");
 
        // Joining Multiple Strings By Using 'add()' Method
        myString.add("Logan");
        myString.add("Magneto");
        myString.add("Storm");
        myString.add("Rogue");
 
        // Displaying The Output String
        System.out.println("StringJoiner with simple delimiter: " + myString);
    }
 
    // Method #2
    public static void joinerWithPrefixSuffix() {
 
        // Passing Hyphen(-) As Delimiter & Opening Bracket "(" As Prefix & Closing Bracket ")" As Suffix
        StringJoiner myDate = new StringJoiner("-", "(", ")");
 
        // Joining Multiple Strings By Using 'add()' Method
        myDate.add("2018");
        myDate.add("Feb");
        myDate.add("01");
 
        // Displaying The Output String
        System.out.println("StringJoiner with Prefix and Suffix: " + myDate);
    }
 
    // Method #3
    public static void listJoiner() {
 
        List<String> dList = new ArrayList<String>();
        dList.add("SUNDAY");
        dList.add("MONDAY");
        dList.add("TUESDAY");
        dList.add("WEDNESDAY");
        dList.add("THURSDAY");
        dList.add("FRIDAY");
        dList.add("SATURDAY");
 
        // Passing The Delimiter
        String days = String.join(",", dList);
 
        // Displaying The Output String
        System.out.println("Join List with Delimiter: " + days);
    }
 
    // Method #4
    public static void collectorJoiner() {
 
        List<String> tList = Arrays.asList("Spring", "Java", "Hibernate", "AngularJs", "MongoDb");
 
        // Passing The Delimiter
        String tutorials = tList.stream().map(t -> t).collect(Collectors.joining(","));
 
        // Displaying The Output String
        System.out.println("Collector Joining: " + tutorials);
    }
 
    // Method #5
    public static void mergeJoiner() {
 
        // Passing Comma(,) As Delimiter & Opening Bracket "(" As Prefix & Closing Bracket ")" As Suffix
        StringJoiner joiner1 = new StringJoiner(",","{","}");
        joiner1.add("one");
        joiner1.add("two");
 
        // Passing Colon(:) As Delimiter & Opening Bracket "(" As Prefix & Closing Bracket ")" As Suffix
        StringJoiner joiner2 = new StringJoiner(":","[","]");
        joiner2.add("three");
        joiner2.add("four");
        joiner2.add("five");
 
        // Displaying The Output String
        StringJoiner mergeStr = joiner1.merge(joiner2);
        System.out.println("Merging two Stringjoiners: " + mergeStr);
    }
}

4. Run the Application

To run the application, developers need to right-click on the class, Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 9: Run Application
Fig. 9: Run Application

5. Project Demo

The above code shows the following logs as output.

01
02
03
04
05
06
07
08
09
10
11
# Logs for 'StringjoinerDemo' #
===============================
StringJoiner with simple delimiter: Logan-Magneto-Storm-Rogue
 
StringJoiner with Prefix and Suffix: (2018-Feb-01)
 
Join List with Delimiter: SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY
 
Collector Joining: Spring,Java,Hibernate,AngularJs,MongoDb
 
Merging two Stringjoiners: {one,two,three:four:five}

That’s all for this post. Happy Learning!

6. Conclusion

In this tutorial, we had an in-depth look at the StringJoiner in Java8. Developers can also use the String.join() method to concatenate multiple strings. This function is flexible as it provides an overloaded version of the String.join() method for the string array elements of the list of strings.

7. Download the Eclipse Project

This was an example of the StringJoiner class in Java8.

Download
You can download the full source code of this example here: Java8Stringjoiner

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button