In Java 8 we have a new Method join() in the Java String class. Java String join() method concatenates the given Strings and returns the concatenated String. Java 8 also introduced a new StringJoiner class for the same purpose.
Java String Join() method Signature
public static 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("-", "This", "is", "a", "String"); // message returned is: "This-is-a-String"
The first argument of this method specifies the delimiter that is used to join multiple strings.
Note that if an element is null, then “null” is added.
Java String join() example
public class Example{ public static void main(String args[]){ //The first argument to this method is the delimiter String str=String.join("^","You","are","Awesome"); System.out.println(str); } }
Output:
You^are^Awesome
Java String join() Example to join list elements by a delimiter
In this example we are joining the elements of a List by a delimiter using join() method.
import java.util.List; import java.util.Arrays; public class Example{ public static void main(String args[]){ //Converting an array of String to the list List list<String> = Arrays.asList("Steve", "Rick", "Peter", "Abbey"); String names = String.join(" | ", list); System.out.println(names); } }
Output:
Steve | Rick | Peter | Abbey
Related Posts:
- Java String concat() example
- Java substring() example
- Java String copyValueOf() example
- Java String intern() example
Leave a Reply