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}.
Approach: This can be achieved with the help of join() method of String as follows. Get the List of String. Form a comma separated String from the List of String using join() method by passing comma ', ' and the list as parameters. Print the String.
How to Convert a Python List into a Comma-Separated String? You can use the . join string method to convert a list into a string. So again, the syntax is [seperator].
Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList); Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .
Using Java 8 you could do it in one line:
String addressID = addresses .stream() .map(a -> String.valueOf(a.addressId)) .collect(Collectors.joining(","));
for converting to comma seperated String use something like this:
String commaSeparatedStr = addresses .stream() .map(String::valueOf) .collect(Collectors.joining(","));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With