Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<Object> into comma separated String

Tags:

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}. 
like image 955
user9193174 Avatar asked Feb 04 '18 05:02

user9193174


People also ask

How do you convert a list to a comma separated string?

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 do you convert a list to a comma separated string in python?

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].

How do I convert a list of strings to a list of objects?

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 .


2 Answers

Using Java 8 you could do it in one line:

String addressID = addresses            .stream()            .map(a -> String.valueOf(a.addressId))            .collect(Collectors.joining(",")); 
like image 89
Kirill Simonov Avatar answered Oct 25 '22 06:10

Kirill Simonov


for converting to comma seperated String use something like this:

String commaSeparatedStr = addresses         .stream()         .map(String::valueOf)         .collect(Collectors.joining(",")); 
like image 29
mohsenJsh Avatar answered Oct 25 '22 07:10

mohsenJsh