0

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.

user6591323
  • 69
  • 2
  • 11

2 Answers2

1

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);
Eritrean
  • 15,851
  • 3
  • 22
  • 28
1

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.

Tobi
  • 2,001
  • 2
  • 27
  • 49
  • Too bad, than @Erithrean's answer won't work either. Nevertheless, you should use named parameters for the query anyways (see my edit). If you do this, you won't have to add the quotes manually. – Tobi Mar 21 '18 at 15:41
  • 1
    But these values, which are then used in an IN clause, come from another query.The OP should use that query directly as a subquery, instead of executing it, getting the result and injecting that into another query. – DodgyCodeException Mar 21 '18 at 15:44
  • 1
    @DodgyCodeException Yes, I absolutely agree that it should be done that way. But I think it's still worth clarifying the misconception of how set parameters in a query, as it is security relevant in other cases. – Tobi Mar 21 '18 at 15:47