49

I would like to ask: how do you convert a Collection to a List in Java?

carlspring
  • 31,231
  • 29
  • 115
  • 197
Mercer
  • 9,736
  • 30
  • 105
  • 170

7 Answers7

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
2

Make a new list, and call addAll with the Collection.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
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
  • 4
    I 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(); 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`. – Matt Ball Sep 29 '10 at 14:34
  • 1
    This 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