Tuesday, May 8, 2018

StringJoiner

I recently came to know about a new feature of java 8 StringJoiner

StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

Simply put, it can be used for joining Strings making use of a delimiter, prefix, and suffix.

This is a final class comes under Object class. It has following methods:


StringJoiner  add(CharSequence newElement)

Adds a copy of the given CharSequence value as the next element of the StringJoiner value.

int length()

Returns the length of the String representation of this StringJoiner.

StringJoiner merge(StringJoiner other)

Adds the contents of the given StringJoiner without prefix and suffix as the next element if it is non-empty.

StringJoiner setEmptyValue(CharSequence emptyValue)

Sets the sequence of characters to be used when determining the string representation of this StringJoiner and no elements have been added yet, that is, when it is empty.


How to use StringJoiner?

  1.  Join String by a delimiter
  2. StringJoiner sj = new StringJoiner(",");
            sj.add("aaa");
            sj.add("bbb");
    
            sj.add("ccc");
            String result = sj.toString(); //aaa,bbb,ccc
    
  3. Join String by a delimiter and starting with a supplied prefix and ending with a supplied suffix.
StringJoiner sj = new StringJoiner("/", "prefix-", "-suffix");
        sj.add("2016");
        sj.add("02");
        sj.add("26");
        String result = sj.toString(); //prefix-2016/02/26-suffix


Happy Reading!

1 comment:

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...