StringJoiner Example with Java Collections

StringJoiner is the goto class when it comes to joining multiple objects with a delimiter. Let us take a look at how to convert a Java Collection to a StringJoiner object.


Example:

package org.code2care.examples;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

public class StringJoinerCollectionsExample {

    public static void main(String[] args) {
        List<String> countriesList = new ArrayList<>();
        countriesList.add("Japan");
        countriesList.add("USA");
        countriesList.add("China");
        countriesList.add("France");

        StringJoiner stringJoiner = new StringJoiner(",");

        for (String country : countriesList) {
            stringJoiner.add(country);
        }

        System.out.println("Countries: " + stringJoiner.toString());
    }
}
Output:

Countries: Japan,USA,China,France

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!