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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap