Java 8 Util API: StringJoiner Example

By Arvind Rai, November 23, 2014
java.util.StringJoiner has been introduced in Java 8. StringJoiner is a util method to construct a string with desired delimiter. If required we can also add prefix and suffix to the final string. To achieve it, StringJoiner is created with two constructor, first is only with delimiter and second has delimiter, prefix and suffix. We can merge two StringJoiner. Find the description and example.

StringJoiner(CharSequence d)

This constructor uses a delimiter to separate the added element.

StringJoiner.add(CharSequence element)

StringJoiner.add method adds element to it. We need to call add method every time as the number of elements to be added.
StringJoinerDemoOne.java
package com.concretepage.util;
import java.util.StringJoiner;
public class StringJoinerDemoOne {
    public static void main(String[] args) {
        StringJoiner sj = new StringJoiner("-");
        sj.add("Ram");
        System.out.println(sj);
        sj.add("Shyam").add("Mohan");
        System.out.println(sj);
    }
} 
Find the output.
Ram
Ram-Shyam-Mohan 

StringJoiner(CharSequence d, CharSequence p, CharSequence s)

This constructor also takes prefix and suffix to add. Prefix and suffix does not depend on the number of added element.

StringJoiner.merge(StringJoiner other)

We can merge two StringJoiner. There will be a primary StringJoiner to which another StringJoiner will be added. Another StringJoiner will not bring its prefix and sufiix while being added in primary StringJoiner.

StringJoiner.length()

StringJoiner.length() gets the length as normal string length method.
StringJoinerDemoTwo.java
package com.concretepage.util;
import java.util.StringJoiner;
public class StringJoinerDemoTwo {
    public static void main(String[] args) {
        StringJoiner sjObj = new StringJoiner(",", "{", "}");
        //Add Element
        sjObj.add("AA").add("BB").add("CC").add("DD").add("EE");
        String output = sjObj.toString();
        System.out.println(output);
        //Create another StringJoiner
        StringJoiner otherSj = new StringJoiner(":", "(", ")");
        otherSj.add("10").add("20").add("30");
        System.out.println(otherSj);
        //Use StringJoiner.merge(StringJoiner o)
        StringJoiner finalSj = sjObj.merge(otherSj);
        System.out.println(finalSj);
        //get length using StringJoiner.length()
        System.out.println("Length of Final String:"+finalSj.length());
    }
} 
Find the output.
{AA,BB,CC,DD,EE}
(10:20:30)
{AA,BB,CC,DD,EE,10:20:30}
Length of Final String:25 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us