Convert a Set of String to a comma separated String in Java


Let us first create a set with string values −

Set<String>set = new HashSet<>(Arrays.asList("One", "Two", "Three", "Four", "Five", "Six"));

Now, convert it to a comma separated string using String.join() −

String str = String.join(", ", set);

Example

Following is the program to convert set of string to a comma separated string in Java −

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      Set<String>set = new HashSet<>(Arrays.asList("One", "Two", "Three", "Four", "Five", "Six"));
      System.out.println("Set = " + set);
      String str = String.join(", ", set);
      System.out.println("Comma separated String: "+ str);
   }
}

Output

Set = [Five, Six, One, Four, Two, Three]
Comma separated String: Five, Six, One, Four, Two, Three

Updated on: 25-Sep-2019

712 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements