In Java, how does one get the values of a HashMap
returned as 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.
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.
You can convert HashMap keys into ArrayList or you can convert HashMap values into ArrayList or you can convert key-value pairs into ArrayList.
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); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With