Reputation: 339
I have a question about hashmaps with multiple keys to value. Let's say I have (key / value )
1/a, 1/b, 1/3, 2/aa, 2/bb, 2/cc.
Would this work?
If it does, could I have a way to loop through it and display all values for only either key 1 or 2?
Upvotes: 1
Views: 5332
Reputation: 1415
Maps will handle multiple keys to one value since only the keys need be unique: Map(key, value)
However one key to multiple values requires s multimap of a map strict of : Map(key, list(values))
Also, whatever you use as a key really should implement a good hadhCode() function if you decide to use a HashMap and/or HashSet
Edit: had to use() instead of <> because my mobile or sof's mobile site editor clobbered the <> symbols....odd
Upvotes: 0
Reputation: 86744
A simple MultiMap would look something like this skeleton:
public class MultiMap<K,V>
{
private Map<K,List<V>> map = new HashMap<K,List<V>>();
public MultiMap()
{
// Define constructors
}
public void put(K key, V value)
{
List<V> list = map.get(key);
if (list == null)
{
list = new ArrayList<V>();
map.put(key, list);
}
list.add(value);
}
public List<V> get(K key)
{
return map.get(key);
}
public int getCount(K key)
{
return map.containsKey(key) ? map.get(key).size() : 0;
}
}
It cannot directly implement Map<K,V>
because put
can't return the replaced element (you never replace). A full elaboration would define an interface MultiMap<K,V>
and an implementation class, I've omitted that for brevity, as well as other methods you might want, such as V remove(K key)
and V get(K key, int index)
... and anything else you can think of that might be useful :-)
Upvotes: 3
Reputation: 17612
You can use a map with lists as values, e.g.:
HashMap<Integer, List<String>> myMap = new HashMap<Integer, List<String>>();
Upvotes: 6
Reputation: 38511
java.util.HashMap
does not allow you to map multiple values to a single key. You want to use one of Guava's Multimap's. Read through the interface to determine which implemented version is suitable for you.
Upvotes: 3