Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 310
Vinay Prajapati Avatar asked Feb 23 '18 18:02

Vinay Prajapati


People also ask

How do you join a stream of strings?

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.

How do you join a list in Java?

In Java, we can use String. join(",", list) to join a List String with commas.

What is prefix and suffix in Java?

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.


2 Answers

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("','", "'", "'"));
like image 96
developer Avatar answered Oct 13 '22 06:10

developer


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()+"'";
like image 30
Hadi J Avatar answered Oct 13 '22 07:10

Hadi J