Thursday 17 September 2015

String.join() method

Since JDK 1.8

String java.lang.String.join(CharSequence delimiter, CharSequence... elements)

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

For example,
String message = String.join(delimiter, element-1, elements-2, ….);

     // message returned is: "Java-is-cool"

Note that if an element is null, then "null" is added.

Returns a new String that is composed of the elements separated by the delimiter

Throws NullPointerException, If delimiter or elements is null.


String java.lang.String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

Iterable that will have its elements joined together.



package core.string;

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

public class StringJoinExample {

       public static void main(String[] args) {
              String message = String.join("-", "Java", "is", "cool");
              System.out.println(message);

              String messageNull = String.join("-", "Java", null, "cool");
              System.out.println(messageNull);

              List<String> list = new ArrayList<String>();
              list.add("Java");
              list.add("is");
              list.add("cool");
              String messageIter = String.join(" : ",list );
              System.out.println(messageIter);
       }
}

Output:
Java-is-cool
Java-null-cool
Java : is : cool

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...