How to join a list elements by ',' using streams with ' as prefix and suffix too

Vinay Prajapati :

I have an insert statement like below

private final COLUMNS = "NAME,TYPE,STATUS,CATEGORY";

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

String insertStatement = String.format("INSERT INTO ifc.documents (%s) VALUES (%s) ",COLUMNS,values); 

I can easily put COLUMNS as no quotes required but for values, my SQL fails and complain about missing quotes for the code above.

So, I tried

 String values = list.stream()
.collect(Collectors.joining("','"));

But it fails with this one as well.So I did a workaround and added another statement prefixing and suffixing a single quote and it started working.

 values = "'"+values+"'";

To be more specific, if i have say "rest", "test" and "best" in list

then expected output is

'rest','test','best'

Anyone knows a better solution for this?

developer :

You can actually use Collectors.joining(CharSequence delimiter,CharSequence prefix,CharSequence suffix) and you can look here for the API.

String values = list.stream().collect(Collectors.joining("','", "'", "'"));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=441677&siteId=1