How do I add and remove elements from a multivalued HashMap?

I am trying to add values ​​to a multivalued HashMap that has the following structure:

Map< Integer, List<Float> > map = new HashMap< Integer, List<Float> >();

      

I really wanted to refer to a specific element (for example, "View Info in Android"), so the value Integer

for HashMap

will contain unique elements ID

, List

from Float

will contain the X coordinate values ​​of the elements. The user can have many items on the screen, they can also have 100 items with the same ID, so the list will contain each item's X coordinate value accordingly.

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 the Float values ​​for the element with ID 1.

I am currently adding List values ​​like this:

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 currently running into is how can I instantiate a new list every time a new id is created.

I would need to create 100 List for 100 items, which is not possible without knowing the number of ids.

Is there a better approach to solve this problem ...

Also I wanted to find a way to remove a specific value of a specific key from HashMap

+3


source to share


2 answers


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 methods to easily add and remove items.

+9


source


You can use Guava Multimap .



+2


source







All Articles