How Join Multiple String into One in Java 8 - String.join() Example

I have been writing about new features of Java SE 8 from quite a sometime. Initially, my focus areas on much talked about lambda expressions and streams, but slowly I realized that Java 8 is not just about them, it's much more than that. It has many more new features and API enhancements which will help Java developers in their day-to-day job as much as lambdas and streams. One of such less talked feature is the ability to join multiple String objects into one separated with any delimiter. It has added a class called StringJoiner in the java.util package which we have seen earlier, but it has also added a new method on String class, the join() method, which finally allows you to join Strings in Java.

You might have faced scenarios in past where you have a list of String or an array of String and you want to join them by a comma.

Unfortunately, Java didn't have anything like Android's TextUtils.join() or JavaScript's Array.join() method which can join String on a delimiter.

Finally, the wait is over. JDK 8 has introduced a join() method which you can use to join any number of arbitrary String, an array of String or a list of String by a delimiter.

Similar to String.split(), it is also a static method and you can call it as String.join(). It has two overloaded versions, one accepts a delimiter and number of String objects as variable arguments and other accepts a delimiter and an Iterable to join elements from array and list.

In this article, I'll show you a couple of examples of how to use join() method of String class to join Strings in Java 8 and you can always look back to a good Java course like The Complete Java MasterClass to understand more about these little gems from Java 8.

It's one of the best course to learn Java and also most up-to-date, recently updated for Java 11 version.




How to join Mulitple String Objects in Java 8

You can use the String.join() method to join a number of String literals, String objects, String elements from an array, or String elements from List, Set or any collection because it accepts an Iterable.

This means all classes which implement this interface can use this join() method to join individual objects. You can also pass the delimiter of your choices like a comma, semicolon, pipe, or colon characters.

Here is an example of String.join() to join String literals by PIPE character

String banks = String.join("|", "Citibank", "Bank of America", "Chase");
System.out.println("banks: " + banks);

Output
banks: Citibank|Bank of America|Chase
You can see that the final String contains all three String literals separated by PIPE delimiter.

here is another example to join all elements of a List by commas

List<String> payCompanies = Arrays.asList("Apple pay", "Samsung Pay", "Paypal");
String wallats = String.join(",", payCompanies);
System.out.println("electronic wallats : " + wallats);

Output
electronic wallets : Apple pay,Samsung Pay,Paypal

and here is the last example of String.join() to join elements of an array in Java:

String[] typesOfCards = {"Credit card", "Debit card", "Master Card"};
String cards = String.join(",", typesOfCards );
System.out.println("cards: " + cards);

Output
cards: Credit card,Debit card,Master Card

You can see that the final String is a combination of all the individual String and they are separated by a comma. This is really handy and you end up using quite often. Btw, if you want to know more about such gems from Java 8 release then I also suggest you join What's New in Java 8 course on Pluralsight.

How Join Multiple String into One in Java 8 - String.join() Example

Btw, you would need a Pluralsight membership to get access this course, which cost around $29 per month or $299 annually (14% discount).

If you don't have Pluralsight membership, I encourage you to get one because it allows you to access their 5000+ online courses on all latest topics like front-end and back-end development, machine learning etc. It also includes interactive quizzes, exercises, and latest certification material.

They also provide a 10-day free trial without any commitment, which is a great way to not just access this course for free but also to check the quality of courses before joining Pluralsight.



Java Program to join String

Here is our complete Java program to demonstrate other features of String.join() method. It's a static method similar to split, so you can directly call them on String literal or just pass the String values you want to join.  The program contains three examples, first to join arbitrary String literals, second to join elements from the list of String, and third to join elements from an array.

package test;

import java.util.Arrays;

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

  public static void main(String[] args) {

    // Joining arbitrary number of String
    String combined = String.join(" and ", "LinkedIn", "Microsoft");
    System.out.println("string joined by and : " + combined);

    // joining elements from a list of String
    String joined = String
        .join("|", Arrays.asList("Java", "Android", "Oracle"));
    System.out.println("String joined by pipe from list : " + joined);

    // joining String elements of an array
    String[] biggies = { "Apple", "Google", "Amazon" };
    String fromArray = String.join(",", biggies);
    System.out.println("String joined by comma from array: " + fromArray);

  }

}

Output
string joined by and : LinkedIn and Microsoft
String joined by pipe from list : Java|Android|Oracle
String joined by comma from array: Apple,Google,Amazon


That's all about how to use String.join() method in Java 8 to join String. Now, no need to use any third party library e.g. Google Guava or Apache commons, you can join String by just using JDK itself. If you come across any other detail about String.join() method, please let us know. It's one of the interesting methods which will be soon as popular as String.split() is at the moment.


Further Learning
The Complete Java MasterClass
Java SE 8 for Really Impatient
From Collections to Streams in Java 8 Using Lambda Expressions


Other Java 8 tutorials you may like to explore
  • 5 Free Courses to learn Java 8 and 9 (courses)
  • How to use forEach() method in Java 8 (example)
  • 10 Examples of Stream in Java 8 (example)
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to convert List to Map in Java 8 (solution)
  • Difference between abstract class and interface in Java 8? (answer)
  • 10 Free Courses for Experienced Java Programmers (courses)
  • How to sort the may by values in Java 8? (example)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • Top 5 Course to master Java 8 Programming (courses)
  • Java 8 Interview Questions and Answers (questions)

Thanks for reading this article so far. If you like this Java 8 tutorial then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

P.S.: If you just want to learn more about new features in Java 8 then please see the course What's New in Java 8. It explains all the important features of Java 8 e.g. lambda expressions, streams, functional interfaces, Optional, new Date Time API and other miscellaneous changes.

2 comments:

  1. Looks like your payCompanies and typesOfCards output needs to be swapped.

    ReplyDelete
    Replies
    1. Indeed, thanks for pointing out, swapped now.

      Delete