String join() method in Java 8

Java 8 added overloaded static join methods that join multiple strings into a single string.

 

String join(CharSequence delimiter, CharSequence… elements)

 
This method takes a delimiter and a sequence of strings to be joined and provides the joined string.
 

Example :

 

public class StringJoin {

  public static void main(String[] args) {

    String str1 = "Hello";
    String str2 = "World";
    
    //Using join() method added in JDK 8

    String joinedString = String.join(" ", str1, str2);
    System.out.println(joinedString);
  }

}


 

Output :

 
Hello World
 
 

Note: If we provide null in place of a string, then “null” is added.

 

Example:

 

    String str1 = "Hello";
    String str2 = null;
    
    // Method 4 : Using join() method added in JDK 8

    String joinedString = String.join("-", str1, str2);
    System.out.println(joinedString);

 

Output :

 
Hello-null
 

String join(CharSequence delimiter, Iterable elements)

 
This method takes a delimiter and an Iterable, for example, a List or Set.
 

Example :

 

package com.topjavatutorial;

import java.util.ArrayList;
import java.util.List;

public class StringJoin2 {

  public static void main(String[] args) {

    List<String> list = new ArrayList<String>();
    list.add("Hello");
    list.add("World");
    //Using join() method added in JDK 8

    String joinedString = String.join(" ", list);
    System.out.println(joinedString);
  }

}


 

Output:

 
Hello World
 
 
Again, if an individual element is null, then “null” is added.
 

Example :

 

    List<String> list = new ArrayList<String>();
    list.add("Hello");
    list.add(null);
    //Using join() method added in JDK 8

    String joinedString = String.join(" ", list);
    System.out.println(joinedString);

 

Output:

 
Hello null
 
 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

One comment

  1. […] may also like the following posts :   String join() method in Java8   Java + operator and Operator […]

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: