craiggantry
craiggantry

Reputation: 13

How do i add individual values to list within a hashmap?

I've looked at so many examples but can't quite grasp this.

I need to create a method that inserts new values into already populated lists within my hashmap. I can't for the life of me figure out how to do. Can anyone help as well as explain how it works?

I've already created methods that populate the maps etc. I just can't figure out how to create a method that inserts just values for particular keys.

import java.util.*;


public class Singles
{
   // instance variables - replace the example below with your own
   private Map<String, List<String>> interests;

   /**
    * Constructor for objects of class Singles
    */
   public Singles()
   {
      // initialise instance variables
      super();
      this.interests = new HashMap<>();
   }


}

Upvotes: 1

Views: 137

Answers (1)

duffymo
duffymo

Reputation: 308743

This is a multi-map.

public class MultiMap {
    private Map<String, List<String>> multiMap = new HashMap<>();

    public void put(String key, String value) {
        List<String> values = (this.multiMap.containsKey(key) ? this.multiMap.get(key) : new ArrayList<>());
        values.add(value);
        this.multiMap.put(key, values);
    }
}

Upvotes: 1

Related Questions