Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Collection to List?

I am using TreeBidiMap from the Apache Collections library. I want to sort this on the values which are doubles.

My method is to retrieve a Collection of the values using:

Collection coll = themap.values(); 

Which naturally works fine.

Main Question: I now want to know how I can convert/cast (not sure which is correct) coll into a List so it can be sorted?

I then intend to iterate over the sorted List object, which should be in order and get the appropriate keys from the TreeBidiMap (themap) using themap.getKey(iterator.next()) where the iterator will be over the list of doubles.

like image 617
Ankur Avatar asked Feb 24 '09 01:02

Ankur


People also ask

Can I cast a collection to a list?

Use addAll to Convert Collection Into List in Java. addAll() is a method provided in the collections framework that we can use to convert a collection to a list. The elements from the collection can be specified one by one or as an array.

How do you convert from one collection to another in Java?

Thanks to the Collection framework in Java, copying collections from one to another is extremely easy. Since every Collection class implements a Collection interface that defines the addAll() method, which can be used to create a collection from contents of another collection.


1 Answers

List list = new ArrayList(coll); Collections.sort(list); 

As Erel Segal Halevi says below, if coll is already a list, you can skip step one. But that would depend on the internals of TreeBidiMap.

List list; if (coll instanceof List)   list = (List)coll; else   list = new ArrayList(coll); 
like image 62
Paul Tomblin Avatar answered Oct 18 '22 15:10

Paul Tomblin