Skip to content
Advertisement

Exploring with Java streams required to read and convert the format of strings [closed]

I am trying Java streams to read a List of Strings, splitting the list to some format like shown below For ex: this is in my input string –

[APPLE, MANGO]

I am trying to convert the above data to this format

('APPLE', 'MANGO')

Trying to convert this using java streams, with the below piece code

String.join(",", list.stream().map(item ->   "'"+item+"'").collect(Collectors.toList()));

The output I am getting is like below

('APPLE, MANGO')

But I am expecting like

('APPLE', 'MANGO')

Can anyone correct my java code to get above required format?

Context to this issue is

Trying to create a SQL Query like

Select * from TEST_TABLE where ID IN (‘APPLE’, ‘MANGO’))

where as IN CLAUSE Parameters is an ArrayList<String>();

But with my code i am getting the out put as

Select * from TEST_TABLE where ID IN ('APPLE, MANGO'))

IN clause is not properly formatted , ‘ is missing

Advertisement

Answer

Maybe you could do something like:

String.format("(%s)", list.stream().map(s -> String.format("'%s'", s)).collect(Collectors.joining(",")));

EDITED:

String.format("%s)", list.stream().map(s -> String.format("'%s'", s)).collect(Collectors.joining(",")));

EDITED ANOTHER TIME:

With these additional info this is what you need:

String query = "Select * from TEST_TABLE where ID IN (%s)"

query = String.format(query, list.stream().map(s -> String.format("'%s'", s)).collect(Collectors.joining(",")));

System.out.println(query);
Advertisement