Java 8 StringJoiner

By Yashwant Chavan, Views 1401, Date 05-Nov-2016

Learn how to use Java 8 StringJoiner class to join String elements using delimiter, prefix and suffix values.

tags java

Syntax

Java 1.8 introduce new class java.util.StringJoiner to constructs a string by a joining a delimiter and starting with a supplied prefix and ending with a suffix value. It has two overloaded versions one accepts only delimiter parameter and another accepts delimiter, prefix and suffix values.

StringJoiner.add(CharSequence c) adds a copy of the given CharSequence value as the next element of the StringJoiner value. If newElement is null, then "null" is added.

public StringJoiner(CharSequence delimiter) 
public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

Java 8 String Joiner Examples

package com.technicalkeeda.app;

import java.util.StringJoiner;

public class Java8StringJoiner {

    public static void main(String[] args) {
        StringJoiner stringJoiner = new StringJoiner(",");
        String str = stringJoiner.add("one").add("two").add("three").toString();

        System.out.println(str);

        stringJoiner = new StringJoiner(",", "[ ", " ]");
        stringJoiner.add("Yashwant").add("Chavan");
        str = stringJoiner.toString();

        System.out.println(str);

    }
}

output

one,two,three
[ Yashwant,Chavan ]
Yashwant Chavan

Yashwant Chavan

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan@gmail.com