32

I am getting list of Address objects from the DB call.

ArrayList<Address> addresses = new ArrayList<>();

Each Address has an int addressId property.

I am writing an update query where in the IN clause I am sending this whole list of Address objects and I am getting ibatis TypeException. How can I convert List<Address> to a comma separated string which can be sent to update query?

My update query looks like:::

Update tablename set postcode = #{postCode} where id in #{addressID}.
Michele Dorigatti
  • 811
  • 1
  • 9
  • 17
user9193174
  • 363
  • 1
  • 4
  • 12

8 Answers8

57

Using Java 8 you could do it in one line:

String addressID = addresses
           .stream()
           .map(a -> String.valueOf(a.addressId))
           .collect(Collectors.joining(","));
Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
16

for converting to comma seperated String use something like this:

String commaSeparatedStr = addresses
        .stream()
        .map(String::valueOf)
        .collect(Collectors.joining(","));
mohsenJsh
  • 2,048
  • 3
  • 25
  • 49
  • 3
    In case someone need a comma separated of variable inside Address object, use the getter inside map `.map(c -> String.valueOf(c.getName()))` – Roy Ryando Jan 10 '20 at 04:26
8

String#join, which accepts delimiter String and Iterable elements (which is List in your case)

 List<String> strings = new LinkedList<>();
 strings.add("Java");
 strings.add("is");
 strings.add("cool");
 String message = String.join(",", strings); //pass delimiter and List
 //message returned is: "Java,is,cool"
Ravi
  • 30,829
  • 42
  • 119
  • 173
3

Iterate over the address objects, retrieve their ID and create a String. Something like this:

StringBuilder sb = new StringBuilder();

for (Address a: adresses) {
  sb.append(a.getId());
  sb.append(", ");
}

String ids = sb.toString();
Marit
  • 2,399
  • 18
  • 27
2
String.join(", ", addresses) ;
Usman
  • 949
  • 9
  • 12
1
StringBuilder addressIds = new StringBuilder("");
for(Address address : addresses){
  if (addressIds.length() > 1)  
    addressIds.append(", ");
  addressIds.append("'").append(address.id()).append("'");
}

//in this method you can directly send the string in Update tablename + set postcode + where id in <String>.
methodOfUpdateInQuery(addressIds.toString());
Zico
  • 2,349
  • 2
  • 22
  • 25
1

The format required can be obtained using toString() and replaceAll() methods (using regular Expressions).

String addressString = addresses.toString().replaceAll("[ \\[ \\] ]", "");
Nithin
  • 748
  • 1
  • 10
  • 27
1

List of int - let Java do it:

String tmp = addresses.toString();
String csList = tmp.substring(1, tmp.length()-1);
xavierz
  • 335
  • 1
  • 11