March 5, 2022

Java String join() Method With Examples

In Java 8 join() method has been added to the Java String class that joins together the given strings using the specified delimiter.

Read Also: Java StringJoiner Class With Method Examples

Java String join() method

There are two variants of the join() method-

  • public static String join(CharSequence delimiter, CharSequence... elements)- This method returns a new String created by joining together the elements using the specified delimiter.
  • public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)- Here elements is an Iterable that will have its elements joined together and delimiter is a sequence of characters that is used to separate each of the elements in the resulting String.

Java String join() method examples

1. Joining 3 strings using space (" ") as delimiter and using colon ":" as delimiter.

public class JoinStrings {
  public static void main(String[] args) {
    String str1 = "Java";
    String str2 = "Python";
    String str3 = "Scala";

    // joining using space as delimiter
    String joinedStr = String.join(" ", str1, str2, str3);
    System.out.println("Joined String- " + joinedStr);
    // joining using colon as delimiter
    joinedStr = String.join(":", str1, str2, str3);
    System.out.println("Joined String- " + joinedStr);
  }
}
Output
Joined String- Java Python Scala
Joined String- Java:Python:Scala

2- Joining List elements using join() method. Using the second variant of join method where an iterable is passed as parameter we can join List elements (or Set).

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class JoinStrings {
  public static void main(String[] args) {
    List<String> list = Arrays.asList("Java", "Python", "Scala");

    // joining list elements using colon as delimiter
    String joinedStr = String.join(":", list);
    System.out.println("Joined String- " + joinedStr);
    
    // joining set elements using pipe as delimiter
    Set<String> strings = new LinkedHashSet<>(list);
    joinedStr = String.join("|", strings);
    System.out.println("Joined String- " + joinedStr);
  }
}
Output
Joined String- Java:Python:Scala
Joined String- Java|Python|Scala

That's all for the topic Java String join() Method With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment