Thursday, May 11, 2023

10 Examples of Joining String in Java - String.join vs StringJoiner

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 a comma to produce another String "Sony, Apple, Google", there is not an easy way to do it in Java. You need to iterate through an 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. Still, you won't find any 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.

A join()  method is added into the 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.

And, If you are new to the Java world, then I also recommend you go through these best Java Programming Courses to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.





10 Examples of Joining Stream in Java for Beginners

Without wasting any more of your time, here are examples of using Stringjoiner class and the String.join() method to join multiple strings by comma, colon or any other separator in Java. 

1. 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 programmers might confuse StringJoiner and StringBuilder or StringBuffer, but there is a big difference between them. StringBuilder provides an append() method, but StringJoiner provides the join() method.

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

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

Example 1 - Joining multiple String by comma

Here is an example of joining a number of String by comma in Java:
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 the 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 these Java 8 online courses to learn more about the StringJoiner class. These courses will help to learn miscellaneous enhancement done in Java 8 with a brief summary and useful examples, which is very handy for a busy Java programmer.


2. 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's class for joining Strings. There are two overloaded versions of the join() method, one which accepts CharSequence elements as variable arguments, so you can pass as many String, StringBuffer, or StringBuilder 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 a list of String or an array of String in Java.


3. Joining a couple of String

Here is an example of joining any arbitrary number of Strings using the String.join() method. The second argument is variable arguments which means 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 the String.join() method; no loop was required.

String Join Example in Java 8




4. Joining all String from an array

Now, let's see how we can join all String elements from an array in Java. Before Java 8, we have to loop through an array and use a StringBuilder to append all elements into one and then finally convert that to String using the toString() method.

Now, you don't need all that; just pass the array and a delimiter of your choice to the 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 the delimiter, semi-colon, in our case.



5. 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 a List but any Collection class unless it's implementing an Iterable interface.  The same String.join() method is used to combine elements of List as it was used for array in the 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 the given list, and each element is separated by a comma, the delimiter we have passed.



6. Joining String using Collectors in Stream

JDK 8 also provides a joining 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 commas as instructed to joining Collector.  See these Java Stream API Courses learn more about Streams and Collectors in JDK 8.



7. How to Join String in Java 7 or Before

There is no built-in join() method on the Java version before Java 8, so you need to write your own or use third-party libraries like Google Guava or Apache commons and their StringUtils class join String. Alternatively, you can use this method to join String in Java 7 and earlier versions.

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 method a List of String and a delimiter of your choice; it will return a String where elements of a list are joined by a given delimiter.



Java Program to join String in JDK 8

Our complete sample Java program demonstrates 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 the addition of String.join() method joining String has become very easy in Java 8. If you are not running on JDK 8 yet, 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 (see here)
  • 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 (see here)
  • 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)

Thank you all, If you have any questions or doubt, feel free to ask in comments. 

5 comments:

  1. Nice Article and good information.

    ReplyDelete
  2. @Anonymous, thanks, Glad that you like this article.

    ReplyDelete
  3. To solution for java7 and before, even simpler is:

    StringBuilder sb = new StringBuilder();
    String deli = "";
    for (String item : list) {
    sb.append(deli);
    sb.append(item);
    deli = delimeter;
    }
    return sb.toString();

    ReplyDelete
  4. StringJoiner provides add() method, join method is in String class.


    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.

    ReplyDelete