Java 8 StringJoiner Example

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

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts