Reputation: 262
I've been given a test-driven development problem (I need to make it work based on the junit methods provided) based on implementing a HashMap that uses a strings for the keys and ArrayLists for the values. The key needs to be able to support one or more corresponding values. I need to set up my methods in a way that I can add or subtract values from the hash, and then see the updated contents of the hash. My struggle is taking info provided from the unit method shown below (exercising myClass and it's addingMethod method) methods) and getting it put properly into the hash.
void add() {
myClass = new MyClass("key1", "value1");
myClass.addingMethod("blargh", "blarghvalue");
myClass.addingMethod("blargh2", "uglystring");
myClass.addingMethod("blargh", "anotherstring");
//and so on and so on............
For my end result, when I print out the results of myClass, I need to see something like: {blargh=[blarghvalue, anotherstring], blargh2=uglystring}
I need to be able to add to this, and remove values as well.
I'm very new to java collections (obviously). I can get things to work if they only have a 1 to 1 relationship, and the hashmap is 1:1. So a very simple addingMethod like this:
public void addingMethod(String key, String value) {
hashMap.put(key, value);
Will get a string string hashmap, but of course if I reuse a key with a new key-value pair, the original key-value gets stepped on and goes away. When it comes to working with hashmaps and arraylists dynamically though, and beyond a 1:1 key:value relationship, I'm lost.
Upvotes: 1
Views: 5437
Reputation: 46209
It sounds like you need a MultiMap
, which is provided by Google's great Guava libraries
:
A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.
Upvotes: 3
Reputation: 19185
What you need is Map<String, List<String>>
and inside put check if entry exists if yes then add to list.
Declare your Map like below
Map<String, List<String>> map = new HashMap<String, List<String>>();
Note that syntax of adding Method
should be same as put
public List<String> put(String key, String value) {
if (!map.containsKey(key)) {
return map.put(key, new ArrayList<String>());
}
List<String> list = map.get(key);
list.add(value);
return map.put(key, list);
}
Upvotes: 3