Problem description: We have given a Set that contains String elements. Our task is to convert this set of string to a comma separated string in Java.
For example:
Input: Set<String> = ["Apple", "Orange", "Mango"] Output: "Apple, Orange, Mango" Input: Set<String> = ["J", "a", "v", "a"] Output: "J, a, v, a"
Example 1: Using String.join() method
We can do this conversion using join() method of String class. The string join() method returns a string by combining all the elements of an iterable collection(list, set etc), separated by the given separator.
Here we will pass the set to the String join() method and separator as comma (,). This will join all the set elements with the comma and return a comma separated string.
import java.util.*; public class JavaExample { public static void main(String args[]) { // Set of Strings Set<String> animalSet = new HashSet<>(); animalSet.add("Lion"); animalSet.add("Tiger"); animalSet.add("Monkey"); animalSet.add("Rabbit"); // Displaying Set elements System.out.println("Set of Strings: " + animalSet); // Convert the Set of Strings to comma separated String String str = String.join(", ", animalSet); // Display the Comma separated String as output System.out.println("Comma Separated String: "+ str); } }
Output:
Example 2: Using Stream API
Stream API was introduced in java 8. In the following example, we are using stream API for the conversion.
import java.util.*; import java.util.stream.Collectors; public class JavaExample { public static void main(String args[]) { // Set of Strings Set<String> animalSet = new HashSet<>(); animalSet.add("Lion"); animalSet.add("Tiger"); animalSet.add("Monkey"); animalSet.add("Rabbit"); // Displaying Set elements System.out.println("Set of Strings: " + animalSet); // Using Stream API for conversion // collect() method returns the result of the // intermediate operations performed on the stream String str = animalSet.stream().collect( Collectors.joining(",")); // Display the Comma separated String as output System.out.println("Comma Separated String: "+ str); } }
Output:
Set of Strings: [Monkey, Lion, Rabbit, Tiger] Comma Separated String: Monkey,Lion,Rabbit,Tiger