HashMap <String, ArrayList>, adding an ArrayList with new key-based values
I was given a test development problem (I need to get it to work based on the provided junit methods) based on a HashMap implementation that uses strings for keys and ArrayLists for values. The key must be able to support one or more relevant values. I need to configure my methods so that I can add or subtract values ββfrom the hash, and then see the updated contents of the hash. My fight takes the information provided from the unit method below (using the myClass methods and the addMethod method) and correctly putting it in 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 myClass results, I need to see something like: {blargh = [blarghvalue, anotherstring], blargh2 = uglystring}
I need to be able to add and remove values ββto this.
I am very new to java collections (obviously). I can get the job to work if they only have a 1 to 1 relationship and the hash map is 1: 1. So, a very simple addMethod method:
public void addingMethod(String key, String value) { hashMap.put(key, value); It will get the hashmap string of the string, but of course, if I reuse the key with a new key-value pair, the original key value will come and go. When it comes to working with hashmaps and arraylists dynamically, albeit outside of the 1: 1 key: value relationship, I get lost.
It looks like you need a MultiMap , which is provided by Google with excellent Guava libraries :
A collection that looks like a map, but that can associate multiple values ββwith a single key. If you call put (K, V) twice with the same key but different values, the multimap contains key mappings for both values.
You need Map<String, List<String>> and check inside if the record exists, if so, add it to the list.
Declare your card as shown below
Map<String, List<String>> map = new HashMap<String, List<String>>(); Note that the syntax of the adding Method should be the 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); }