Searching...
Saturday, 28 November 2015

Java 8 StringJoiner Example

21:19
Java 8 introduced java.util.StringJoiner , it is a util method to construct a string with desired delimiter. Also we can add prefix and suffix to the final string. To achieve this, StringJoiner has two constructor, first is only with delimiter and second has delimiter, prefix and suffix. Here is one simple example which is using StringJoiner.

Example


package com.vinod.test;

import java.util.StringJoiner;

public class Java8StringJoinerExample {

public static void main(String[] args) {

StringJoiner sj = new StringJoiner("-");
sj.add("Honda").add("Toyota").add("Ford");
System.out.println(sj);

// String joiner with prefix and suffix
StringJoiner sj1 = new StringJoiner("-", "My Vehicle List start",
"My Vehicle List end");
sj1.add("Honda").add("Toyota").add("Ford");
System.out.println(sj1);

// Merge two string joiner
System.out.println(sj.merge(sj1));

}

}

Output

Honda-Toyota-Ford
My Vehicle List startHonda-Toyota-FordMy Vehicle List end
Honda-Toyota-Ford-Honda-Toyota-Ford

0 comments: