Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Map to List in Java?

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?

like image 418
Javaa Avatar asked Jun 22 '09 11:06

Javaa


People also ask

Can we convert HashMap to ArrayList?

In order to do this, we can use the keySet() method present in the HashMap. This method returns the set containing all the keys of the hashmap. This set can be passed into the ArrayList while initialization in order to obtain an ArrayList containing all the keys.


2 Answers

List<Value> list = new ArrayList<Value>(map.values()); 

assuming:

Map<Key,Value> map; 
like image 132
cletus Avatar answered Oct 09 '22 02:10

cletus


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 
like image 35
coobird Avatar answered Oct 09 '22 04:10

coobird