Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include duplicate keys in HashMap? [duplicate]

Tags:

I need linked and multiple keys in key set. I tried this:

LinkedHashMap<Integer, String> map = new LinkedHashMap< Integer,String>();  map.put( -1505711364,"4"); map.put(294357273, "15"); map.put(-1593134417, "28"); map.put(-1231165758, "45"); map.put(121046798, "58"); map.put(294357273, "71"); map.put(-1593134417, "82"); map.put(-1231165758, "95"); map.put(121046798, "108"); 

I need duplicate keys which is order preserved. What is the way to do this??

like image 263
LoneWolf Avatar asked Sep 20 '13 17:09

LoneWolf


People also ask

Can we insert duplicate keys in HashMap?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

How do you keep keys duplicated in maps?

As we can see, if we try to insert two values for the same key, the second value will be stored, while the first one will be dropped. It will also be returned (by every proper implementation of the put(K key, V value) method): Map<String, String> map = new HashMap<>(); assertThat(map. put("key1", "value1")).

What if we add duplicate keys in hash table?

You can't add duplicate keys to hashtables, because hashtables by design can only contain unique keys. If you need to store duplicate key/value pairs, use arrays.


1 Answers

You can't have duplicate keys in a Map. You can rather create a Map<Key, List<Value>>, or if you can, use Guava's Multimap.

Multimap<Integer, String> multimap = ArrayListMultimap.create(); multimap.put(1, "rohit"); multimap.put(1, "jain");  System.out.println(multimap.get(1));  // Prints - [rohit, jain] 

And then you can get the java.util.Map using the Multimap#asMap() method.

like image 183
Rohit Jain Avatar answered Sep 28 '22 20:09

Rohit Jain