Home » Java » Core Java » Java 8 StringJoiner

About Sjoerd Schunselaar

Sjoerd Schunselaar

Java 8 StringJoiner

At the release of Java 8 the most attention went to the Lamda’s, the new Date API and the Nashorn Javascript engine. In the shade of these, there are smaller but also interesting changes. Amongst them is the introduction of a StringJoiner. The StringJoiner is a utility to delimit a list of characters or strings. You may recognize the code below:

 
 
 
 
 
 

String getString(List<String> items)
    StringBuilder sb = new StringBuilder();
    for(String item : items) {
        if(sb.length != 0) {
            sb.append(",");
        }
        sb.append(item);
    }
    return sb.toString();
}

This can be replaced by these lines in Java 8:

String getString(List<String> items) {
    StringJoiner stringJoiner = new StringJoiner(", ");
    for(String item : items) {
        stringJoiner.add(item);
    }
    return stringJoiner.toString();
}

If you already know how to use streams, the following code will reduce some obsolete lines.

String getString(List<String> items) {
    StringJoiner stringJoiner = new StringJoiner(", ");
    items.stream().forEach(stringJoiner::add);
    return stringJoiner.toString();
}

Another valuable addition is to set a prefix and a suffix. They can be set as second and third parameter in the StringJoiner constructor. For example:

String getString(List<String> items) {
    StringJoiner stringJoiner = new StringJoiner(", ", "<<", ">>");
    items.stream().forEach(stringJoiner::add);
    return stringJoiner.toString();
}

This code can return for example:

 <<One, Two, Tree, Four>>

Another way to compose a new String from an iterable is using the Join method on the String class. The Join method supports a seperator, but no prefix and suffix. You can use it as follows:

 String result = String.join(", ", "One", "Two", "Three");

The result will be:

 One, Two, Three
Reference: Java 8 StringJoiner from our JCG partner Sjoerd Schunselaar at the JDriven blog.
(0 rating, 0 votes)
You need to be a registered member to rate this.
2 Comments Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
karanRakesh Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
Rakesh
Guest
Rakesh

Thanks for sharing!

karan
Guest
karan

This is a really cool and much needed feature.