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??
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.
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")).
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.
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.
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