Reputation: 3750
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?
Upvotes: 8
Views: 10569
Reputation: 4520
PersonList[] personlist = restTemplate.getForObject(url, PersonList[].class);
ArrayList<PersonList> personlist2 = Arrays.asList(personlist)
Upvotes: 0
Reputation: 206796
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));
Upvotes: 17
Reputation: 311188
The easiest way would be to use Arrays.asList
:
Collection<PersonList> personlist2 = Arrays.asList(personlist)
Upvotes: 3