3

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.

Suganya Selvarajan
  • 962
  • 1
  • 11
  • 33
  • 2
    `String.join(",", packageCategories)` should work – ernest_k Dec 07 '18 at 09:02
  • Please show the full code ([mcve]). The code you show is not responsible for the error, as it will work fine since `Set` is of type `Iterable extends CharSequence>` (see [documentation](https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#join(java.lang.CharSequence,java.lang.Iterable))). – Zabuzard Dec 07 '18 at 09:03
  • Please share the code where you are performing the display. It looks like you are printing out the collection instead of each item. You will need a loop for that. –  Dec 07 '18 at 09:07
  • @magerine : Not necessarily. – Nicholas K Dec 07 '18 at 09:11

2 Answers2

5

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("[\\[\\]]", "")
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
5

You need to use StringUtils not String

    StringUtils.join(packageCategories,",")
Monis Majeed
  • 1,358
  • 14
  • 21