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:

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

Output:
WOW:{Steve Jobs,Warren Buffet,Dovincy}
wow:{}
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");
sj1.add("Dovincy");
System.out.println("First String: "+sj1.toString());
StringJoiner sj2 = new StringJoiner("","[","]");
System.out.println("Second String: "+sj2);
sj2.merge(sj1);
System.out.println("Second String: "+sj2);

Output:
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");
System.out.println(items);

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

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.  

0 comments:

Post a Comment

 
Top