Convert java.util.Collection to java.util.List

April 19, 2013 by Sandeep Bhardwaj | Tags:


List list;  
if (collection instanceof List)  
{  
  list = (List)collection;  
}  
else  
{  
  list = new ArrayList(collection);  
}  

Generic way (java 1.5<=)

public <E> List<E> collectionToList(Collection<E> collection)  
 {  
  List<E> list;  
  if (collection instanceof List)  
  {  
   list = (List<E>) collection;  
  }  
  else  
  {  
   list = new ArrayList<E>(collection);  
  }  
  return list;  
 }  

Without Generics (java 1.4>=)

public List collectionToList(Collection collection)  
 {  
  List list;  
  if (collection instanceof List)  
  {  
   list = (List) collection;  
  }  
  else  
  {  
   list = new ArrayList(collection);  
  }  
  return list;  
 }