Convert Java Set<String> to Java Comma Separated String

Suganya Selvarajan :

I have a java Set

private Set<String> packageCategories;

This has the value ['Abc','Def']. I want to display the value of packageCategories in the UI which now displays as ['Abc','Def'] but I want to display it as simply 'Abc', 'Def.

I tried

String.join(",", packageCategories);
context.put("packageCategories", packageCategories);

I am getting compilation error

 incompatible types: java.util.Set<java.lang.String> cannot be converted to java.lang.String.

How can I achieve this? I searched in StackOverflow and it has answers to convert List to comma separated string. But I didn't find any answer to convert Set to comma separated string.

The answer given in Fastest way to put contents of Set<String> to a single String with words separated by a whitespace? does not work for me.

PS: I am not a JAVA Developer.

Nicholas K :

You can achieve the same using streams :

String collect = packageCategories.stream().collect(Collectors.joining(","));

With your original code snippet you can use :

String.join(",", packageCategories).replaceAll("[\\[\\]]", "")

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130517&siteId=1