What is the best way to convert a Map<key,value> to a list<value>? Just iterate over all values and insert them in a list or am I overlooking something?
List<Value> list = new ArrayList<Value>(map.values());
assuming:
Map<Key,Value> map;
a list of what ?
Assuming map is your instance of Map
map.values() will return a Collection containing all of the map's values
map.keys() will return a Set containing all of the map's keys
The issue here is that Map
has two values (a key and value), while a List
only has one value (an element).
Therefore, the best that can be done is to either get a List
of the keys or the values. (Unless we make a wrapper to hold on to the key/value pair).
Say we have a Map
:
Map<String, String> m = new HashMap<String, String>();
m.put("Hello", "World");
m.put("Apple", "3.14");
m.put("Another", "Element");
The keys as a List
can be obtained by creating a new ArrayList
from a Set
returned by the Map.keySet
method:
List<String> list = new ArrayList<String>(m.keySet());
While the values as a List
can be obtained creating a new ArrayList
from a Collection
returned by the Map.values
method:
List<String> list = new ArrayList<String>(m.values());
The result of getting the List
of keys:
Apple
Another
Hello
The result of getting the List
of values:
3.14
Element
World
I guess you want to convert the values contained in the Map to a list? Easiest is to call the values() method of the Map interface. This will return the Collection of value objects contained in the map. Note that this collection is backed by the Map object and any changes to the Map object will reflect here. So if you want a separate copy not bound to your map object, simply create a new List object like an ArrayList passing the value collection as below.
ArrayList list = new ArrayList(map.values());