In every programming language and in many applications developers have to put together list of values, frequently these are comma delimited lists but they can also incorporated with other string separators. Java SE 8 has two new utils for this one is StringJoiner class and another static method of string class name join which are newly introduced in Java 8 using these features we can easily concatenate or add strings and also contains so many uses. Now we are going to have discussion on this topics.

String Joiner
Sample code:

import java.util.StringJoiner;
public class StringJoinEx {
public static void main(String[] args) {
StringJoinEx sjEx = new StringJoinEx();
private void go() {
StringJoiner sj1 = new StringJoiner(",","{","}");
sj1.add("Steve Jobs");
sj1.add("Warren Buffet");
StringJoiner sj2 = new StringJoiner("","{","}");
System.out.println("Ouch.. Where are my curly braces? "+sj2.toString());
System.out.println("Thats how setEmptyValue method works.");

WOW:{Steve Jobs,Warren Buffet,Dovincy}
Ouch.. Where are my curly braces? 
Thats how setEmptyValue method works.

As we see in the output constructor allows strings to be separated by commas with prefix and suffix.

Then we represented displaying of empty string as {}.

When we use method setEmptyValue method it returns an empty string without any prefix and suffix.

We left with one method named merge().

Code Snippet:

StringJoiner sj1 = new StringJoiner(",","{","}");
sj1.add("Steve Jobs");
sj1.add("Warren Buffet");
System.out.println("First String: "+sj1.toString());
StringJoiner sj2 = new StringJoiner("","[","]");
System.out.println("Second String: "+sj2);
System.out.println("Second String: "+sj2);

First String: {Steve Jobs,Warren Buffet,Dovincy}
Second String: []
Second String: [Steve Jobs,Warren Buffet,Dovincy]

Here in this case first string is added to the second string ignoring its prefix and suffix.

Another nice thing is that string joiner can be used directly from the string class using join method lets see the example.

Code Snippet:

String items = new String.join(",","fridge","washing machine","oven");

String[] states = {" Andhra Pradesh"," Assam","Bihar"};
String stateslist = new String.join(",",states);

This is one thing that we need to notice.

Previously we used '+' operator, StringBuffer and StringBuilder to add two strings. We can use Perf4j which of the above methods performs better in which scenario.

Note: Jprofiler is a performance tool in industry standard.  


Post a Comment