Java String Join – Different ways

When we develop a web application, a lot of times,  we may need to join a list or an array with a space of comma. In Java, we have to write boilerplate code to do that.

To get rid of those, we can use the Apache common utils or guava utils. Refer the below code. It’s pretty simple if we use those utils effectively. Humans tend to make errors. So if we write the code for ourselves, we may cause some issues while doing those. All these utils and its methods are thoroughly tested and verified. So it’s good to use these unless reinvent yourself.

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StringJoinUtils {

    public static void main(String[] args) {
        List stringList = new ArrayList(Arrays.asList(new String[]{"Apple","Orange","Banana"}));
        //Apache commons
        System.out.println(StringUtils.join(stringList, ":"));
        //Guvava utils
        //Java 8
        System.out.println(String.join(":", stringList));

If we use Java 8, we can use the String.join method.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s