Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap: One Key, multiple Values

Tags:

java

How I can get the third value for the first key in this map? Is this possible?

like image 878
Sunscreen Avatar asked Nov 22 '11 15:11

Sunscreen


People also ask

Can one key have multiple values in HashMap?

HashMap can be used to store key-value pairs. But sometimes you may want to store multiple values for the same key. For example: For Key A, you want to store - Apple, Aeroplane.

Can a Key have multiple values in a map?

The Map interface stores the elements as key-value pairs. It does not allow duplicate keys but allows duplicate values. HashMap and LinkedHashMap classes are the widely used implementations of the Map interface. But the limitation of the Map interface is that multiple values cannot be stored against a single key.

How HashMap store different values with same key?

If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values. Show activity on this post. I use Map<KeyType, Object[]> for associating multiple values with a key in a Map. This way, I can store multiple values of different types associated with a key.


1 Answers

Libraries exist to do this, but the simplest plain Java way is to create a Map of List like this:

Map<Object,ArrayList<Object>> multiMap = new HashMap<>(); 
like image 154
solendil Avatar answered Sep 22 '22 08:09

solendil