Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one convert a HashMap to a List in Java?

In Java, how does one get the values of a HashMap returned as a List?

like image 717
sparkyspider Avatar asked Mar 30 '11 07:03

sparkyspider


People also ask

Can a HashMap value be a list?

Idea behind associating Multiple values with same key is to store another Collection as Value in the HashMap. This can be a List or Set or any other Map too.

Can a HashMap key be a list?

Yes you can have ArrayList s as a keys in a hash map, but it is a very bad idea since they are mutable. If you change the ArrayList in any way (or any of its elements), the mapping will basically be lost, since the key won't have the same hashCode as it had when it was inserted.

Is it possible to convert keys in the Map to array or ArrayList?

You can convert HashMap keys into ArrayList or you can convert HashMap values into ArrayList or you can convert key-value pairs into ArrayList.


2 Answers

HashMap<Integer, String> map = new HashMap<Integer, String>(); map.put (1, "Mark"); map.put (2, "Tarryn"); List<String> list = new ArrayList<String>(map.values()); for (String s : list) {     System.out.println(s); } 
like image 58
sparkyspider Avatar answered Oct 10 '22 13:10

sparkyspider


Assuming you have:

HashMap<Key, Value> map; // Assigned or populated somehow. 

For a list of values:

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

For a list of keys:

List<Key> keys = new ArrayList<Key>(map.keySet()); 

Note that the order of the keys and values will be unreliable with a HashMap; use a LinkedHashMap if you need to preserve one-to-one correspondence of key and value positions in their respective lists.

like image 43
maerics Avatar answered Oct 10 '22 14:10

maerics