Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Java Set<String> to Java Comma Separated String [duplicate]

Tags:

java

string

set

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.

like image 212
Suganya Selvarajan Avatar asked Nov 18 '25 11:11

Suganya Selvarajan


1 Answers

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("[\\[\\]]", "")
like image 195
Nicholas Kurian Avatar answered Nov 21 '25 01:11

Nicholas Kurian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!