How do I add and remove items from a multivalue HashMap?

collections, hashmap, java

Solution

How about this :

public class multivalueHashmap {
    private Map< Integer, List<Float> > map = new HashMap< Integer, List<Float> >();

    public void add(Integer id, Float value){
        if(!map.containsKey(id)){
            map.put(id, new ArrayList<Float>());
        }
        map.get(id).add(value);
    }

    public void delete(Integer id, Float value){
        if(!map.containsKey(id)){
            return;
        }
        map.get(id).remove(value);
    }
}

This way you can use the methods to easily add and remove items.

Problem

I am trying to add values to a multivalue HashMap which is of the following structure: ``` Map< Integer, List<Float> > map = new HashMap< Integer, List<Float> >(); ``` I actually wanted to hold a reference to a particular item (A View's info in Android for e.g.), so the `Integer` value of the `HashMap` will contain the items `ID` which is unique, the `List` of `Float`s will contain the items X coordinate values. The user can have many items on the screen, he can also have 100 items with same ID, so accordingly the List will contain each Items X coordinate value. To be more clear my HashMap will contain the following data {1,{200, 400.5, 500.6 ...}}, where 1 is the key and the rest are Float values for Item with ID 1. Right now I add the List values as follows... ``` List<Float> list = new ArrayList<Float>(); list.add(x_coord_1); list.add(x_coord_2); list.add(x_coord_3) map.put(1, list); ``` The problem I am facing now is figuring out as of how can I instantiate a new List everytime a new ID is created.. I would have to create 100 List's for 100 items which is not feasible, not knowing the number of ID's.. Is there a better approach to solve this issue... Also I wanted to find a way to delete a specific value of a particular key from the `HashMap`

Original source