Friday, 18 April 2014

Java 8 StringJoiner

Java 8 introduces a new String manipulation API StringJoiner. Using StringJoiner, one can append multiple string values with the pre-defined format like commas, prefix and suffix. This syntax is very similar to the one used with the another frameworkGuava.


StringJoiner Constructors

This class takes two constructors:
  1. StringJoiner (delimiter) – Adds only the delimiter between the strings
  2. StringJoiner (delimiter, prefix, suffix) – It adds delimiter, prefix and suffix for each string.

StringJoiner Methods

StringJoiner class defines four methods.
  1. add(CharSequence newEle) – This method adds the new string into the object.
  2. length() – It returns the total length of the string joiner object.
  3. setEmptyOutput(CharSequence charSeq).
  4. toString() – Returns the current value.

StringJoiner Example

package com.java.example;

import java.util.StringJoiner;

/**
 * Java 8 StringJoiner Example
 * @author mohan
 *
 */
public class StringJoinerExample {
 public static void main (String args[]){
  // Only delimiter example
  StringJoiner joiner = new StringJoiner(",");
  joiner.add("Java").add("Scala").add("Groovy");
  System.out.println("Delimeter Only:  " + joiner);

  // Delimiter with prefix and suffix example
  joiner = new StringJoiner(",","[","]");
  joiner.add("Mohan").add("Singh").add("Thakur");
  System.out.println("Delimeter, Suffix and Prefix:  " + joiner);

  //Finding the total length of string joiner
  System.out.println("Length of StringJoiner : "+ joiner.length());
 }
}

Delimeter Only:  Java,Scala,Groovy
Delimeter, Suffix and Prefix Example :  [Mohan,Singh,Thakur]
Length of StringJoiner : 20





















No comments:

Post a Comment

Getting started with Elasticsearch and Node.js

  In this article we're going to look at using Node to connect to an Elasticsearch deployment, index some documents and perform a simple...