10 Examples of Joining String in Java 8 - StringJoiner and String.join

Datetime:2016-08-23 00:37:58          Topic: Java8           Share

It's quite common in day to day programming to join Strings e.g. if you have an array or List of String let's say {Sony, Apple, Google} and you want to join them by comma to produce another String "Sony, Apple, Google", there is not an easy way to do it in Java. You need to iterate through array or list and then use a StringBuilder to append a comma after each element and finally to remove the last comma because you don't want a comma after the last element. A JavaScript-like Array.join() method or join() method of Android's TextUtils class is what you need in this situation, but you won't find any of such method on String , StringBuffer , StringBuilder , Arrays,  or Collections class until Java 8. Now, you have a class called StringJoiner which allows you to join multiple String by a delimiter.

There is also a join() method is added into String class  to convert an array of String or a list of String joined by a delimiter of your choice. In this article, we'll see a couple of examples of joining String in Java 8, which will teach you how to use both StringJoiner and String.join() methods.

Btw, if you are keen to learn new features of Java 8 apart from major attraction like lambda expression and date and time API, then see the Java SE 8 for Really Impatient book by Cay S. Horstmann. He has explained miscellaneous enhancement done in Java 8 with the brief summary and useful examples, which is very handy for a busy Java programmer.

Joining String using StringJoiner

The JDK 8 has added another text utility class called StringJoiner in java.util package. This class allows you to join arbitrary String by a delimiter. It also allows you to add a prefix or suffix by providing overloaded constructors.

Some programmer might confuse between StringJoiner and StringBuilder or StringBuffer , but there is a big difference between them. StringBuider provides append() method but StringJoiner provides join() method.

The append() method doesn't know that you don't need to add delimiter after the last element but join() does. So you don't need to handle either first or last element in joining loop anymore.

Here is a couple of examples of joining multiple Strings using StringJoiner class:

Example 1 - Joining number of String by comma

StringJoiner joiner = new StringJoiner(", ");
joiner.add("Sony")
joiner.add("Apple")
joiner.add("Google")
String joined = joiner.toString();

This will print

Sony, Apple, Google

You can even shorthand above code in one line as shown below:

String joined = new StringJoiner(",").add("Sony")
                       .add("Apple").add("Google").toString();

From these examples, you can see how easy it has become to join multiple String in Java 8. You can also see Java SE 8 for Really Impatient to learn more about StringJoiner class.

Joining String using String.join() method

JDK 8 also added a convenient join() method on java.lang.String class to join Strings. This method internally uses StringJoiner class for joining Strings. There are two overloaded versions of join() method, one which accepts CharSequence elements as variable arguments, so you can pass as manyString,StringBuffer, orStringBuilder as you want.

This is used to join any number of arbitrary String as it accepts individual String as a variable argument, so you can pass as many String as you want.

The second version of join() accepts a CharSequence delimiter and Iterable of CharSequence , which means you can use this to join alist of String or anarray of String in Java.

Joining a couple of String

Here is an example of joining any arbitrary number of String using String.join() method. The second argument isvariable arguments which mean you can pass any number of String as you want.

String combined = String.join(" ", "Java", "is", "best");
System.out.println("combined string: " + combined);

Output
combined string: Java is best

You can see that we have combined three String by space by using String.join() method, no loop was required.

Joining all String from array

Now, let's see how we can join all String elements from an array in Java. If you remember, prior to Java 8 we have toloop through array and use aStringBuilder to append all elements into one and then finally convert that to String using toString() method.

Now, you don't need all that, just pass the array and a delimiter of your choice to String.join() method and it will do that for you.

String[] typesOfFee = {"admin fee", "processing fee", "monthly fee"};
String fees = String.join(";", typesOfFee);

Output
admin fee;processing fee;monthly fee

You can see that all three elements of the array are joined together and separated by thedelimiter which was semi-colon in our case.

Joining String from a List

Joining all elements of a list in Java is not very different than joining elements from an array. You can pass not just aList but anyCollection class unless its implementing Iterable interface.  Same String.join() method is used to combine elements of List  as it was used for array in previous example.

List<String> typesOfLoan = Arrays.asList("home loan", "personal loan",
           "car loan", "balance transfer");
String loans = String.join(",", typesOfLoan);
System.out.println("joining list elements: " + loans);

Output
home loan,personal loan,car loan,balance transfer

You can see the result is a long String containing all elements of given List and each element is separated by acomma, the delimiter we have passed.

Joining String using Collectors in Stream

JDK 8 also provides ajoining Collector, which you can use to join String from a Stream as shown below.

List<String> list = Arrays.asList("life insurance", "health insurance",   "car insurance");
String fromStream = list.stream()
     .map(String::toUpperCase)
     .collect(Collectors.joining(", "));

Output
LIFE INSURANCE, HEALTH INSURANCE, CAR INSURANCE

You can see that all elements from the Stream are combined using comma as instructed to joining Collector.  See Java 8 in Action to learn more about Streams and Collectors in JDK 8.

How to Join String in Java 7 or Before

Well, there is no built-in join() method on Java version prior to Java 8, so you need to write your own or you can use third party library like Google Guava or Apache commons and theirStringUtils class to join String. Alternatively, you can use this method to join String in Java 7 and earlier version.

public static String join(List<String> list, String delimeter) {
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (String item : list) {
            if (first) {
                first = false;
            } else {
                sb.append(delimeter);
            }
            sb.append(item);
        }
        return sb.toString();
    }

You can pass this methoda List of String and adelimiter of your choice, it will return a String where elements of a list are joined by given delimiter.

Java Program to join String in JDK 8

Here is our complete sample Java program to demonstrate how you can use both StringJoiner and String.join() method to join multiple String objects by a separator.

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

/**
 * Java Program to demonstrate how to use StringJoiner and String.join() method
 * to join individual String and String form list and array.
 */
public class StringJoinerTest {

    @SuppressWarnings("empty-statement")
    public static void main(String[] args) {

        // Joining String in Java using StringJoiner
        // Example 1 - joining stirng by comma
        StringJoiner joiner = new StringJoiner(",");
        String joined = joiner.add("Sony").add("Apple").add("Google").toString();
        System.out.println("joined String by a comma: " + joined);

        
        // Example 2 - let's join String by pipe
        StringJoiner joinByPipe = new StringJoiner("|");
        String pipe = joinByPipe.add("iPhone").add("iPhone6").add("iPhone6S").toString();
        System.out.println("joined String by pipe: " + pipe);

        
        //Exmaple 3 - Joining using String.join(). It internally
        // uses StringJoiner though 
        String bestCreditCards = String.join(",", "Citibank", "Bank Of America", "Chase");
        System.out.println("bestCreditCards: " + bestCreditCards);

        
        // You can use this to create path in file system e.g.
        String pathInLinux = String.join("/", "", "usr", "local", "bin");
        System.out.println("path in Linux : " + pathInLinux);

        String pathInWindows = String.join("\\", "C:", "Program Files", "Java");
        System.out.println("path in Windows : " + pathInWindows);

        
        // Example 4 - Joint Stirng from a List
        List<String> typesOfLoan = Arrays.asList("home loan", "personal loan",
                "car loan", "balance transfer");
        String loans = String.join(",", typesOfLoan);
        System.out.println("joining list elements: " + loans);

        
        // Example 5 - Joining String from array with a delimeter
        String[] typesOfFee = {"admin fee", "processing fee", "monthly fee"};
        String fees = String.join(";", typesOfFee);
        System.out.println("joining array elements: " + fees);

        
        // Example 6 - Joining String using Collectors
        List<String> list = Arrays.asList("life insurance", "health insurance", "car insurance");
        String fromStream = list.stream()
                .map(String::toUpperCase)
                .collect(Collectors.joining(", "));
        System.out.println("joining stream elements : " + fromStream);

        
        // Example 7 - manually prior to Java 8
        List<String> magic = Arrays.asList("Please", "Thanks");
        System.out.println("joined : " + join(magic, ","));;
    }

    /**
     * Java method to join String of a List
     *
     * @param list
     * @param delimeter
     * @return String containing all element of list or array joined by
     * delimeter
     */
    public static String join(List<String> list, String delimeter) {
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (String item : list) {
            if (first) {
                first = false;
            } else {
                sb.append(delimeter);
            }
            sb.append(item);
        }
        return sb.toString();
    }
}

Output
joined String by a comma: Sony,Apple,Google
joined String by pipe: iPhone|iPhone6|iPhone6S
bestCreditCards: Citibank,Bank Of America,Chase
path in Linux : /usr/local/bin
path in Windows : C:\Program Files\Java
joining list elements: home loan,personal loan,car loan,balance transfer
joining array elements: admin fee;processing fee;monthly fee
joining stream elements : LIFE INSURANCE, HEALTH INSURANCE, CAR INSURANCE
joined : Please,Thanks

That's all about how to join String in Java 8 . You can see with the introduction of StringJoiner and addition of String.join() method joining String has become very easy in Java 8. Though, if you are not running on JDK 8 yet then you can use the utility method join() I have shared in this article. It uses StringBuilder to join String from array and list.

Other Java 8 tutorials for busy developers:

  • 10 Example of Lambda Expression in Java 8 (seehere)
  • 10 Example of Stream API in Java 8 (see here)
  • 10 Example of forEach() method in Java 8 (example)
  • 20 Example of LocalDate and LocalTime in Java 8 (seehere)
  • 10 Example of converting a List to Map in Java 8 (example)
  • How to use Stream.flatMap in Java 8(example)
  • How to use Stream.map() in Java 8 (example)
  • 5 Books to Learn Java 8 and Functional Programming (list)




About List