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

DZone 's Guide to

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!

· Java Zone ·
Free Resource

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("/");

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:


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(",");

        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);  



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.

java ,java 8 ,java 8 string ,join ,string ,string.join ,stringjoiner

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

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}