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 theNullPointerException
exceptionpublic 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.
Method | Description |
---|---|
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!
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
.
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.
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
.
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
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <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
.
A new pop window will open where we will enter the package name as: 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
.
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
.
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
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!
5. Project Demo
The above code shows the following logs as output.
# 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.
You can download the full source code of this example here: Java8Stringjoiner