VOOZH about

URL: https://www.javacodegeeks.com/2014/12/java-8-stringjoiner.html

⇱ 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.
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

Thank you!

We will contact you soon.

Tags
Java 8
πŸ‘ Photo of Sjoerd Schunselaar
Sjoerd Schunselaar
December 18th, 2014Last Updated: December 17th, 2014
2 61 1 minute read
Subscribe

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

2 Comments
Oldest
Newest Most Voted
Rakesh
11 years ago

Thanks for sharing!

0
Reply
karan
11 years ago

This is a really cool and much needed feature.

0
Reply
Back to top button
Close
wpDiscuz