Today, i want to show you some Java 8 Join String examples. I am sure you were in a situation in which you wanted to join multiple strings. Java 8 added a new class called StringJoiner. As the name suggests we can use this class to join strings. Beside, Java 8 also added the joining Collector for the new Stream API.
Let’s dig deeper via examples:
1. StringJoiner
Here is two examples: join string by a delimiter and join string with prefix and suffix
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class JoinStringDemo { public static void main(String args[]) { //Join String by a delimiter StringJoiner joiner = new StringJoiner(","); joiner.add("java"); joiner.add("php"); joiner.add("nodejs"); String result = joiner.toString(); System.out.println(result); //Join String by a delimiter and combine prefix and suffix StringJoiner joiner2 = new StringJoiner("/", "[", "]"); joiner2.add("2017"); joiner2.add("11"); joiner2.add("21"); String result2 = joiner2.toString(); System.out.println(result2); } } |
Output
1 2 |
java,php,nodejs [2017/11/21] |
2. String.join
We’re using String.join() method to join a String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class JoinStringDemo2 { public static void main(String args[]) { //Join String by a delimiter String result = String.join("-", "2017", "10", "31"); System.out.println(result); //Join a List by a delimiter List<String> list = Arrays.asList("java", "php", "nodejs", "c#"); String result2 = String.join(", ", list); System.out.println(result2); } } |
Output
1 2 |
2017-10-31 java, php, nodejs, c# |
3. Collectors.joining
If you concern about joining objects to string, don’t worry just use the Collectors.joining method.
In this example, we are consume the POJO as below
1 2 3 4 5 6 |
public class People { public int age; public String gender; public String name; //getter and setter } |
Demo program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class JoinStringDemo3 { public static void main(String args[]) { //Join a List by a delimiter List<String> list = Arrays.asList("java", "php", "nodejs", "c#"); String result = list.stream().map(x -> x).collect(Collectors.joining(" | ")); System.out.println(result); //Join a List<Object> by a delimiter People a = new People(28, "M", "Mr A"); People b = new People(25, "M", "Mr B"); People c = new People(21, "M", "Mr C"); People d = new People(21, "M", "Mr D"); Collection<People> list2 = Arrays.asList(a, b, c, d); String result2 = list2.stream().map(x -> x.getName()).collect(Collectors.joining(", ", "{", "}")); System.out.println(result2); } } |
Output
That’s all about the Java 8 Join String examples.
References
Stream – Collectors.joining JavaDoc
StringJoiner JavaDoc
Download the complete source code, click link below
JoinStringExample.zip (306 downloads)