DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples
  • Proper Java Exception Handling
  • Generics in Java and Their Implementation

Trending

  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • Concourse CI/CD Pipeline: Webhook Triggers
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  1. DZone
  2. Data Engineering
  3. Data
  4. Two Ways to Join String in Java 8: StringJoiner and String.join Examples

Two Ways to Join String in Java 8: StringJoiner and String.join Examples

You can finally join the String in Java 8 without using a third-party library!

By 
Javin Paul user avatar
Javin Paul
·
May. 15, 19 · Presentation
Likes (21)
Comment
Save
Tweet
Share
46.8K Views

Join the DZone community and get the full member experience.

Join For Free

Joining multiple String literals or objects into one is a common programming requirement, and you will often find situations where you need to convert a list of String or a Collection of String into a CSV String for your application. For a long time, JDK API has no way to join multiple String literals or objects together, which forces programmers to write hacks like looping through all String objects and manually joining them using String concatenation to create the final, joined String. Even though this approach worked, it was filled with errors and hacks; you need to be careful not to add delimiter before the first element and after the last element, which often caused issues, particularly for new Java developers.

But the bigger problem with that approach was that everyone needed to re-invent the wheel. Since it was a very common requirement, you found many programmers writing the same routines and making the same mistakes, often ending in StackOverflow to solve their problems.  Thankfully, Java 8 solved this problem once for all.

The JDK 8 API provides a couple of more ways to join Strings like you can join String by using the StringJoiner class or you can join the String by calling the String.join() method.

In this article, we'll explore ways to join string, understand the differences between them, pros and cons of each approach, when to use StringJoiner, and when String.join() is a better option.

Joining String Using StringJoiner in Java 8

The JDK 8 API has added a new class called java.util.StringJoiner, which allows you to join more than one String using a specified delimiter or joiner. For example, you can join multiple strings separated by comma ( ,) to create a CSV String, Or, even better, you can create a full path for a directory in Linux by joining String using forward slash (/) as explained by Cay. S. Horstmann in the Java SE 9 for the Impatient, my favorite book to learn Java.

Here is an example:

StringJoiner joiner = new StringJoiner("/");
joiner.add("usr");
joiner.add("local");
joiner.add("bin");


This will give you a string likeusr/local/bin, which you can pass it to any program. You can further add a  / using prefix if you want to use it as an absolute path or if you need a relative path.

One more advantage of StringJoiner is the fluent API it offers, which allows you to write code in one line. For example, the above code can be re-written using fluent methods of StringJoiner:

String result= new StringJoiner("/").add("usr").add("local").add("bin");


This will print:

"usr/local/bin"


Joining String Using join() Method in Java 8

The problem with StringJoiner is that you need to know that there is a StringJoiner class. But what if you can directly join the String with a more popular java.lang.String class itself? Well, that's what Java designers also thought, and so, they added a static join() method to join the String right from the String class itself.

Here is an example of using String.join() method to join multiple String literals in Java:

  String colonSeparatedValue = String.join(":", "abc", "bcd", "def");
  System.out.println("colon separated String : " + colonSeparatedValue);


This will print the following String:

colon separated String : abc:bcd:def


This is quite good because now you don't need to worry about not adding delimeter at the start or removing it from the end. This is one of the common problems you face while manually joining multiple Strings together in a loop separated by a delimiter, as shown earlier in my example of generating CSV String in Java.

Another advantage of the String.join() method is that you can now directly convert a list of String into a CSV String in Java, without writing any manual code. Here is an example of how to do it:

 List mylist = Arrays.asList("London", "Paris", "NewYork");
        String joined = String.join("||", mylist);
        System.out.println("Joined String : " + joined);


This will print the following String:

Joined String : London||Paris||NewYork


Cool, isn't it?

Two Ways to Join String in Java 8

Here are two ways to join String in Java 8, the first example uses the StringJoiner class while the second example uses String.join() method, a static utility method added on java.lang.String in JDK 8.

package test;

import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;

/**
 * Java program      ADVERTISEMENT                           to show how to join String in Java 8.
 * There are two ways to do that in Java 8, by using StringJoiner or
 * by using join() method of String class.
 * @author Javin
 */

public class Test {

    public static void main(String args[]) {

        // StringJoiner can join multiple String using any delimiter
        // Let's create a CSV String by joining Stirng using comma
        StringJoiner joiner = new StringJoiner(",");
        joiner.add("one");
        joiner.add("two");
        joiner.add("three");

        System.out.println("Comma separated String : " + joiner.toString());

        // You can combine all three lines into one because
        // StringJoiner provides a fluent interface
        StringJoiner delimitedString = new StringJoiner("|").add("id").add("name"); 
        System.out.println("Pipe delimited String : " + delimitedString);

        // 2nd Example: You can also join String by String.join() method
        // By far, this is the most convenient method to join Strings
        // in Java.    

        String csv = String.join(":", "abc", "bcd", "def");
        System.out.println("colon separated String : " + csv);


        // You can even use String.join() method to join contents of
        // ArrayList, Array, LinkedList or any collection, actually
        // any container which implements Iterable interface
        List mylist = Arrays.asList("London", "Paris", "NewYork");
        String joined = String.join("||", mylist);
        System.out.println("Joined String : " + joined);  

    }

}

Output
Comma separated String : one,two,three
Pipe delimited String : id|name
colon separated String : abc:bcd:def
Joined String : London||Paris||NewYork


That's all on two ways to join String in Java 8. Now, you can finally join the String in Java 8 without using a third-party library, and you also have options to use the class that makes the most sense for you. In general, the join() method of the String class is more convenient because you can directly call and pass both delimeter and individual String objects that need to be joined.

You don't need to create another object like StringJoiner. It also allows you to join String from a Collection class, like ArrayList or LinkedList, which means you can create a comma-separated String from an ArrayList of String. How cool is that?

Related Java 8 Tutorials

If you are interested in learning more about new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:

  • Java 8 Interview Questions Preparation Course (free)
  • 5 Books to Learn Java 8 from Scratch (books)
  • 5 Online Course to Learn Java 8 better (courses)
  • What is the default method in Java 8? (example)
  • How to use Stream class in Java 8 (tutorial)
  • How to convert Stream to List and Map in Java 8 (tutorial)
  • How to sort the map by keys in Java 8? (example)
  • How to use filter() method in Java 8 (tutorial)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to convert List to Map in Java 8 (solution)
  • Difference between abstract class and interface in Java 8? (answer)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • How to use peek() method in Java 8 (example)
  • How to sort the may by values in Java 8? (example)
  • 5 Free Courses to learn Java 8 and 9 (courses)

Thanks for reading this article! If you enjoyed it, then please share it with your friends and colleagues. And if you have any questions or suggestions, then please drop a comment below.

Strings Java (programming language) Data Types Joins (concurrency library)

Published at DZone with permission of Javin Paul, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples
  • Proper Java Exception Handling
  • Generics in Java and Their Implementation

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!