In this short post, we will be covering Java 8 StringJoiner feature and will explore what are the different features and how this can be used more effectively with Java 8 Stream API.
Java 8 StringJoiner
Joining multiple strings in a very common tasks in day to day programming activity. There was no direct way to join multiple String in Java (Other than using the third party API’s). Java 8 Introduced a new class StringJoiner which can be used to join multiple Strings.StringJoiner
is a kind of a Collector
.With the help of this class we can join more than one string with a specific delimiter, it also provides the option to add prefix and suffix to the final output. This article is focused on the Java 8 StringJoiner class and it’s different features.
1. StringJoiner Example – Joining String by Delimiter
StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.In this example, we will use the Java 8 StringJoiner class to concatenate multiple strings.
1.1 Using Delimiter
One of the common use cases of the StringJoiner is to use a delimiter to join strings.
StringJoiner joiner = new StringJoiner(",");
joiner.add("Sunday");
joiner.add("Monday");
joiner.add("Tuesday");
System.out.println(joiner.toString());
Here is our Junit
Test
@Test
public void stringJoinerTest(){
StringJoiner joiner = new StringJoiner(",");
joiner.add("Sunday");
joiner.add("Monday");
joiner.add("Tuesday");
assertEquals("Sunday,Monday,Tuesday", joiner.toString());
}
2. StringJoiner Example 2 : Using Delimiter, Prefix and Suffix
StringJoiner also provides the way to predefined prefix
and suffix
in addition to the delimiter
.
public static void joinerWithDelimiterWithPrefixAndSuffix(){
StringJoiner joiner = new StringJoiner(",", "Prefix-", "-Suffix");
joiner.add("Sunday");
joiner.add("Monday");
joiner.add("Tuesday");
joiner.add("Wednesday");
//display output
System.out.println(joiner.toString());
}
Output
Prefix-Sunday-Monday-Tuesday-Wednesday-Suffix
3. StringJoiner Example 3 – Join Multiple StringJoiner
We can also merge multiple StringJoiner
using StringJoiner’s merge()
method
StringJoiner joiner1= new StringJoiner("|");
StringJoiner joiner2= new StringJoiner(";");
StringJoiner joiner3= new StringJoiner(";");
joiner2.add("one");
joiner2.add("two");
joiner1.merge(joiner2);
joiner3.add("three");
joiner3.add("four");
joiner1.merge(joiner3);
System.out.println(joiner1.toString());
Output
one;two|three;four
4. String.join()
StringJoiner
is used internally by two static String.join
methods
String output= String.join("-", "2017","09","30");
2017-09-30 //output
List<String> list= Arrays.asList("one","two","three");
String output = String.join("-", list);
one-two-three //output
5. Collectors.joining
StringJoiner
can be easily used with the new Java 8 Collectors. It’s an indirect way to work with the Java 8 StringJoiner class.
List<Customer> customers = Arrays.asList(
new Customer("John", "Smith"),
new Customer("Umesh", "Awasthi"),
new Customer("Andy", "Flower")
);
final String customerJoin = customers.stream()
.map(Customer::getFirstName)
.collect(Collectors.joining(","));
System.out.println(customerJoin);
Output
John, Umesh, Andy
6. StringJoiner and setEmptyValue Method
In all the above example, we used the toString()
method to get the value from our joiner class.There are few things which you should be aware of:
- A joiner will return en empty string if no prefix ans suffix are provided and String is empty.
- With empty String and prefix ans suffix , joiner will returns a String containing both prefix and suffix.
This will work in most cases, but sometime, we may need a different default value in case string is empty (we don’t want empty string), StringJoiner provides the setEmptyValue()
method to help us set a default value in case the String is empty. Let’s see this with an example:
import java.util.StringJoiner;
public class StringJoinerExample {
public static void main(String[] args) {
StringJoiner joiner = new StringJoiner(",");
System.out.println(joiner.toString()); // empty String
joiner.setEmptyValue("Default Value");
System.out.println(joiner.toString()); //Default Value
}
}
Default value is returned only if the StringJoiner
is empty
import java.util.StringJoiner;
public class StringJoinerExample {
public static void main(String[] args) {
StringJoiner joiner = new StringJoiner(",");
System.out.println(joiner.toString()); // empty String
joiner.setEmptyValue("Default Value");
joiner.add("Checking");
joiner.add("setEmptyValue behaviour");
System.out.println(joiner.toString()); //Checking,setEmptyValue behaviour
}
}
7. Why StringJoiner
There can be a very natural question about why do we need StringJoiner
when we already have StringBuilder
? Or it internally use StringBuilder
to perform most of the operations.With the Java 8 Stream API, StringJoiner is very useful as compared to the StringBuilder.Let’s take an example to understand the difference between using SpringJoiner and StringBuilder.
List<String> list = Arrays.asList("Foo","Bar");
//join string using StringJoiner
String output = list.stream().collect(Collectors.joining(","));
//using StringBuilder
String collectoutput =
list.stream().collect(Collector.of(StringBuilder::new,
(stringBuilder, str) -> stringBuilder.append(str).append(", "),
StringBuilder::append,
StringBuilder::toString));
Summary
In this post, we got an Introduction to Java8 StringJoiner. We explored various features of the StringJoiner class and how to use it to join multiple Strings.We can also think of StringJoiner as a kind of Collector and can be really useful when working with parallel streams.The source code is available on our GitHub repository.
Interesting article.