3

I have a requirement to read the string from a list and join them with ','. Also need to add comma in prefix and suffix of the total output string. Example : If list contans["a","b","c"] then output would be ",a,b,c,".

Now thats perfectly working with Collectors.joining but if the list does not contains any value then also in output strting I am getting ",," as output because prefix and suffix is added.

Now what I want is to avoid the prefix and suffix in case if blank String. So, any suggestion?

List<String> list = new ArrayList<>();
        String result = list.stream().collect(Collectors.joining(",", ",", ","));
        System.out.println(result);

Thanks in Advance.

Souvik
  • 1,219
  • 3
  • 16
  • 38
  • `list.stream().collect(Collectors.joining(",")` or `String.join(",",list);` – Hadi J May 21 '19 at 04:38
  • Cannot answer as this has been marked as a duplicate, but `.collect(() -> new StringJoiner(",", ",", ",").setEmptyValue(""), StringJoiner::add, StringJoiner::merge).toString()` should work. – Bubletan May 21 '19 at 05:17
  • 1
    @Bubletan since this kind of solution is already in [this answer](https://stackoverflow.com/a/36642371/2711488), I added the particular Q&A to the list of duplicates… – Holger May 21 '19 at 10:56
  • I do not think the two listed questions answer this question. But [this later answer](https://stackoverflow.com/a/56560952/859640) does. – John S Jan 27 '20 at 23:48

1 Answers1

1

Just check if the list has elements:

List<String> list = new ArrayList<>();
String result = "";
if (!list.isEmpty())
{
  result = list.stream().collect(Collectors.joining(",",",",","));
}
System.out.println(result);
wilmol
  • 1,429
  • 16
  • 22