Store an array in HashMap
161,508
Solution 1
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);
Solution 2
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});
}
}
Solution 3
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.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on September 30, 2020Comments
-
Admin almost 4 years
i'm new to Java. How can i store an array of integers values in a HashMap, after that i write this HashMap in a txt file but this isn't important at the moment. I can store single fields but not an array. Any ideas ?
public void salveazaObiectulCreat(String caleSpreFisier) { HashMap map = new HashMap(); map.put ("Autorul",numelePrenumeleAutorului); map.put ("Denumirea cartii",denumireaCartii); map.put ("Culoarea cartii",culoareaCartii); map.put ("Genul cartii",gen); map.put ("Limba",limba); map.put ("Numarul de copii",numarulDeCopii); map.put ("Numarul de pagini",numarulDePagini); map.put ("Pretul cartii",pretulCartii); try { File file = new File(caleSpreFisier); FileOutputStream f = new FileOutputStream(file); ObjectOutputStream s = new ObjectOutputStream(f); s.writeObject(map); s.close(); } catch(Exception e){ System.out.println("An exception has occured"); } }