Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store an array in HashMap

Tags:

java

hashmap

People also ask

Can you store an array in a HashMap?

In a HashMap, keys and values can be added using the HashMap. put() method. We can also convert two arrays containing keys and values into a HashMap with respective keys and values.

How do you put an array on a map?

To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.

Can you create a HashMap of array in Java?

You cannot, for example, create an array of a concrete parametrized type with the new operator. The issue relates to the runtime system being unable to guarantee type safety. Arrays are covariant and reified.

How do you add an element to an array in HashMap?

put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.


HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
HashMap<String, int[]> map = new HashMap<String, int[]>();

pick one, for example

HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
map.put("Something", new ArrayList<Integer>());
for (int i=0;i<numarulDeCopii; i++) {
    map.get("Something").add(coeficientUzura[i]); 
}

or just

HashMap<String, int[]> map = new HashMap<String, int[]>();
map.put("Something", coeficientUzura);

Not sure of the exact question but is this what you are looking for?

public class TestRun
{
     public static void main(String [] args)
     {
        Map<String, Integer[]> prices = new HashMap<String, Integer[]>();

        prices.put("milk", new Integer[] {1, 3, 2});
        prices.put("eggs", new Integer[] {1, 1, 2});
     }
}

Yes, the Map interface will allow you to store Arrays as values. Here's a very simple example:

int[] val = {1, 2, 3};
Map<String, int[]> map = new HashMap<String, int[]>();
map.put("KEY1", val);

Also, depending on your use case you may want to look at the Multimap support offered by guava.