I would like to ask: how do you convert a Collection
to a List
in Java?
Asked
Active
Viewed 1.1e+01k times
49

carlspring
- 31,231
- 29
- 115
- 197

Mercer
- 9,736
- 30
- 105
- 170
-
4You want to *say*? Or do you actually want to *know*? :) – BalusC Mar 18 '10 at 15:10
-
It seems that you've no idea on how to use general Collections in Java. What about reading a Tutorial? http://java.sun.com/docs/books/tutorial/collections/intro/index.html – mickthompson Mar 18 '10 at 15:45
-
So , we are waiting for your story. – Artsiom Anisimau Mar 18 '10 at 17:44
7 Answers
70
Collection<MyObjectType> myCollection = ...;
List<MyObjectType> list = new ArrayList<MyObjectType>(myCollection);
See the Collections trail in the Java tutorials.

Michael Myers
- 188,989
- 46
- 291
- 292
55
If you have already created an instance of your List subtype (e.g., ArrayList, LinkedList), you could use the addAll method.
e.g.,
l.addAll(myCollection)
Many list subtypes can also take the source collection in their constructor.

Uri
- 88,451
- 51
- 221
- 321
8
List list;
if (collection instanceof List)
{
list = (List)collection;
}
else
{
list = new ArrayList(collection);
}

Brad Larson
- 170,088
- 45
- 397
- 571

Sandeep Bhardwaj
- 1,310
- 1
- 18
- 24
2
Thanks for Sandeep putting it- Just added a null check to avoid NullPointerException in else statement.
if(collection==null){
return Collections.emptyList();
}
List list;
if (collection instanceof List){
list = (List)collection;
}else{
list = new ArrayList(collection);
}

Vijay Kumar Rajput
- 1,071
- 1
- 10
- 30
0
you can use either of the 2 solutions .. but think about whether it is necessary to clone your collections, since both the collections will contain the same object references

Cshah
- 5,612
- 10
- 33
- 37
-3
Collection
and List
are interfaces. You can take any Implementation of the List
interface: ArrayList LinkedList
and just cast it back to a Collection
because it is at the Top
Example below shows casting from ArrayList
public static void main (String args[]) {
Collection c = getCollection();
List myList = (ArrayList) c;
}
public static Collection getCollection()
{
Collection c = new ArrayList();
c.add("Apple");
c.add("Oranges");
return c;
}

Omnipresent
- 29,434
- 47
- 142
- 186
-
4I suspect you were downvoted because _this won't always work_. Sure, when the `Collection`'s implementing class implements `List` (e.g. `ArrayList`, `LinkedList`...), you're fine. But as soon as you try to do something like `Map
myMap = new HashMap – Matt Ball Sep 29 '10 at 14:34(); List fromMap = (List ) myMap.values();` everything looks fine at compile time - but when you run it, you get `java.lang.ClassCastException: java.util.HashMap$Values cannot be cast to java.util.List`. -
1This is just conceptually totally wrong. You cannot "force" an arbitrary Collection to become a List by casting. – Dirk Hillbrecht Jul 18 '17 at 13:57