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);
       
    }
}


Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.