user6591323
user6591323

Reputation: 69

String Utils join in not working as expected

I have a list of strings which is returned from a query in List A.

I am trying to use String Utils.join to combine the values in the list to a string separated by comma and in quotes. But it is not working as expected.

Values in abcList - [abc, cde, fgh]

abcList.addAll(jdbcTemplate.queryForList(abcSql, String.class));
String abc= StringUtils.join(abcList, "','");
abc = "'" +abc+ "'";

Expected output - 'abc', 'cde', 'fgh'
Actual output - 'abc, cde, fgh'

I am not sure what I am doing wrong here as I want to pass the values form the string abc into query with "IN" condition.

Upvotes: 0

Views: 1835

Answers (2)

Tobi
Tobi

Reputation: 2040

If you are using Java 8 you can use the native method for joining strings.

List<String> list = <get a list of strings somehow>;
String joinedString = String.join("','", list);

See the String.join javadoc

Just as a hint for JDBC queries...you should use named parameters for inserting the values in your query instead of manually constructing the query string.

See this SO post for an example.

Upvotes: 1

Eritrean
Eritrean

Reputation: 16498

As alternative you can also use stream.Collectors.joining

List<String> myList = Arrays.asList("abc","def","ghi");
String joined = myList.stream().collect(Collectors.joining("','", "'", "'"));
System.out.println(joined);

Upvotes: 1

Related Questions