Java Join Strings with Comma Separator


Join Java String using Comma

If you have a list of multiple Strings and you want to join them with a comma separator,

Example 1: Using Java 8 StringJoiner

import java.util.StringJoiner;

public class JavaStringJoinWithComma {
    public static void main(String[] args) {
        
        String string1 = "One";
        String string2 = "Two";
        String string3 = "Three";

        StringJoiner stringJoiner = new StringJoiner(",");
        stringJoiner.add(string1).add(string2).add(string3);
        System.out.println(stringJoiner.toString());
       
    }
}
Output:

One,Two,Three


Example 2: Using Java 8 String.join() method

public class JavaStringJoinWithComma {
    public static void main(String[] args) {
        
        String string1 = "One";
        String string2 = "Two";
        String string3 = "Three";

        String joinedString = String.join(",", string1,string2,string3);
        System.out.println(joinedString);
       
    }
}

One,Two,Three


Example 3: Using Java 8 Stream and Collectors

import java.util.ArrayList;
import java.util.stream.Collectors;

public class JavaStringJoinWithComma {
    public static void main(String[] args) {
        
        String string1 = "One";
        String string2 = "Two";
        String string3 = "Three";

        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add(string1);
        arrayList.add(string2);
        arrayList.add(string3);

        String joinedString = arrayList.stream().collect(Collectors.joining(","));
        System.out.println(joinedString);
       
    }
}

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