简体   繁体   中英

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.

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM