Is there any way to use map or any other collection which allow us to store duplicate keys
with different values...
rather then using a List to store multiple values for same key?
5 Answers
Use Google Guava's MultiMap. This allows multiple values with single key
1 Comment
rather then using a List to store multiple values for same key?Map doesn't allow you to have duplicated keys. That even doesn't make sense.
Possible solution is having list(Collection) of values. Just go for it.If anything stopping you, let us know.
3 Comments
There is a Multimap concept. For example in guava. Multimap in guava
But it's not a part of Collection framework.
If you would not like signature like this Map<String, List<Item>>, you could easily wrap it with object. E.g.
class Items {
private List<Item> items;
public void add(Item i) {}
}
Of course it would not be possible to add items through map instance as map.add("key", item)
Comments
What about the next?:
Map<String, List<String>> map = new HashMap<>();
Add values
// add "key1" and "value1"
if (!map.containsKey("key1")) {
map.put("key1", new ArrayList<String>());
}
map.get("key1").add("value1");
// add "key1" and "value2"
if (!map.containsKey("key1")) {
map.put("key1", new ArrayList<String>());
}
map.get("key1").add("value2");
Get values
List<String> values = map.get("key1");
This with string, but can be for any type. And you don't need additional libraries.
Comments
you can use MultiMap from apache commons collections
Map<Key, List>is definitely the right way to go.map.get(key), and the map contains multiple ofkey. What do you expect to be returned?