Java – How to join List String with commas

In Java, we can use String.join(",", list) to join a List String with commas.

1. Java 8

1.1 String.join

JavaStringExample1.java

package com.mkyong;

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

public class JavaStringExample1 {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("a","b","c");
        String result = String.join(",", list);

        System.out.println(result);

    }

}

Output


a,b,c

1.2 Stream Collectors.joining

JavaStringExample2.java

package com.mkyong;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class JavaStringExample2 {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("a", "b", "c");

        String result = list.stream().collect(Collectors.joining(","));

        System.out.println(result);

    }

}

Output


a,b,c

2. In Old Days

Create a custom method to join the String with separator manually.

JavaStringExample3.java

package com.mkyong;

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

public class JavaStringExample3 {

    public static void main(String[] args) {

        System.out.println(join(",", Arrays.asList("a")));
        System.out.println(join(",", Arrays.asList("a", "b")));
        System.out.println(join(",", Arrays.asList("a", "b", "c")));
        System.out.println(join(",", Arrays.asList("")));
        System.out.println(join(",", null));

    }

    private static String join(String separator, List<String> input) {

        if (input == null || input.size() <= 0) return "";

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < input.size(); i++) {

            sb.append(input.get(i));

            // if not the last item
            if (i != input.size() - 1) {
                sb.append(separator);
            }

        }

        return sb.toString();

    }

}

Output


a
a,b
a,b,c
//empty

References

  1. Java 8 – StringJoiner example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar