Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array to collection in Java?

What I am trying to do here is convert an array to Collection.

How to do this properly?

Here is my array:

PersonList[] personlist = restTemplate.getForObject(url, PersonList[].class);

What I doing there is, I get JSON value and consume with restTemplate, then I put it in PersonList array object, but I want to return the value as Collection. Example:

This is very wrong code that I am trying to present:

Collection<PersonList> personlist2 = personlist

It can't bind the array to collection, cause it's different data type. Can I convert it?

like image 969
Ke Vin Avatar asked May 19 '15 08:05

Ke Vin


2 Answers

You can do this:

List<PersonList> list = Arrays.asList(personlist);

(Is this PersonList itself a list? If not, then why is the class named PersonList instead of Person?).

Note that the list returned by Arrays.asList(...) is backed by the array. That means that if you change an element in the list, you'll see the change in the array and vice versa.

Also, you won't be able to add anything to the list; if you call add on the list returned by Arrays.asList(...), you'll get an UnsupportedOperationException.

If you don't want this, you can make a copy of the list like this:

List<PersonList> list = new ArrayList<>(Arrays.asList(personlist));
like image 56
Jesper Avatar answered Sep 25 '22 12:09

Jesper


The easiest way would be to use Arrays.asList:

Collection<PersonList> personlist2 = Arrays.asList(personlist)
like image 29
Mureinik Avatar answered Sep 23 '22 12:09

Mureinik