[java] How to include duplicate keys in HashMap?

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??

This question is related to java

The answer is


hashMaps can't have duplicate keys. That said, you can create a map with list values:

Map<Integer, List<String>>

However, using this approach will have performance implications.


Map does not supports duplicate keys. you can use collection as value against same key.

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.

Documentation

you can use any kind of List or Set implementation according to your requirement.

If your values might be also duplicate you can go with ArrayList or LinkedList, in case values are unique you can use HashSet or TreeSet etc.


Also In google guava collection library Multimap is available, it is a collection that maps keys to values, similar to Map, but in which each key may be associated with multiple values. You can visualize the contents of a multimap either as a map from keys to nonempty collections of values:

a ? 1, 2
b ? 3  

Example -

ListMultimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("a", "1");
multimap.put("a", "2");
multimap.put("c", "3");

Use Map<Integer, List<String>>:

Map<Integer, List<String>> map = new LinkedHashMap< Integer, List<String>>();

map.put(-1505711364, new ArrayList<>(Arrays.asList("4")));
map.put(294357273, new ArrayList<>(Arrays.asList("15", "71")));
//...

To add a new key/value pair in this map:

public void add(Integer key, String newValue) {
    List<String> currentValue = map.get(key);
    if (currentValue == null) {
        currentValue = new ArrayList<String>();
        map.put(key, currentValue);
    }
    currentValue.add(newValue);
}

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.