Monday, September 18, 2023

How to Join Multiple Strings in Java 8 - String join() Example

Hello guys, I have been writing about the new features of Java SE 8 for quite some time. 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 that will help Java developers in their day-to-day job as much as lambdas and streams. One of such less talked features is the ability to join multiple String objects into one separated with any delimiter. It has added a class called StringJoiner in 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 the 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 String.join(). It has two overloaded versions, one accepts a delimiter and number of String objects as variable arguments and the 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 the join() method of String class to join Strings in Java 8 and you can always look back to these free Java courses to understand more about these little gems from Java 8. It's one of the best courses to learn Java and also most up-to-date, recently updated for the Java 11 version.




How to join Multiple String Objects in Java 8? Example

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 the 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 it quite often. Btw, if you want to know more about such gems from Java 8 release then I also suggest you join these best Java 8 to Java 13 courses to learn new features. 

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




Java Program to join String - Example

Here is our complete Java program to demonstrate other features of the 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 like Google Guava or Apache commons, you can join String by just using JDK itself. If you come across any other detail about the 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.

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)
  • 10 Advanced Core Java courses for Programmers (courses)
  • How to convert List to Map in Java 8 (solution)
  • Best Courses to learn Java Programming for Beginners (best courses)
  • 10 Examples of Stream in Java 8 (example)
  • Difference between abstract class and interface in Java 8? (answer)
  • How to sort the may by values in Java 8? (example)
  • 7 best Courses to learn Data structure and Algorithms (best online courses)
  • 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)

Thanks for reading this article so far. If you like this Java 8 String tutorial then please share it 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 these Java 8 courses from Udemy. It explains all the important features of Java 8 like lambda expressions, streams, functional interfaces, Optional, new Date Time API, and other miscellaneous changes.

And, Now Quiz Time - What is difference between StringJoiner and String.join method in Java?

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

Feel free to comment, ask questions if you have any doubt.