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?
Join stream of strings – examplejoining() method takes separator string as argument and join all the strings in the stream using using this separator. For example, we use comma as separator then this method will result into a comma-separated string. Program output.
In Java, we can use String. join(",", list) to join a List String with commas.
A prefix of a string S is a substring of S that occurs at the beginning of S. A suffix of a string S is a substring that occurs at the end of S. Output the size of the largest such subset. Note that the chosen subset can have a single string also.
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("','", "'", "'"));
Another solution use of String.join method like to this
String result = "'"+String.join("','", list)+"'";
Function<List<String>,String> function = list2->"'".concat(String.join("','",list2)).concat("'");
System.out.println(function.apply(list));
or use reduction like to this
String result = "'"+list.stream().reduce((s, p) -> s + "','" + p).get()+"'";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With