I have a hashmap of the following type
HashMap<String,ArrayList<Integer>> map=new HashMap<String,ArrayList<Integer>>();
The values stored are like this :
mango | 0,4,8,9,12 apple | 2,3 grapes| 1,7 peach | 5,6,11
I want to store as well as fetch those Integers using Iterator or any other way with minimum lines of code.How can I do it?
EDIT 1
The numbers are added at random (not together) as key is matched to the appropriate line.
EDIT 2
How can I point to the arraylist while adding ?
I am getting error while adding a new number 18
in the line map.put(string,number);
Array List can be converted into HashMap, but the HashMap does not maintain the order of ArrayList. To maintain the order, we can use LinkedHashMap which is the implementation of HashMap.
Our variable:
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
To store:
map.put("mango", new ArrayList<Integer>(Arrays.asList(0, 4, 8, 9, 12)));
To add numbers one and one, you can do something like this:
String key = "mango"; int number = 42; if (map.get(key) == null) { map.put(key, new ArrayList<Integer>()); } map.get(key).add(number);
In Java 8 you can use putIfAbsent
to add the list if it did not exist already:
map.putIfAbsent(key, new ArrayList<Integer>()); map.get(key).add(number);
Use the map.entrySet()
method to iterate on:
for (Entry<String, List<Integer>> ee : map.entrySet()) { String key = ee.getKey(); List<Integer> values = ee.getValue(); // TODO: Do something. }
Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); if(pairs.getKey().equals("mango")) { map.put(pairs.getKey(), pairs.getValue().add(18)); } else if(!map.containsKey("mango")) { List<Integer> ints = new ArrayList<Integer>(); ints.add(18); map.put("mango",ints); } it.remove(); // avoids a ConcurrentModificationException }
EDIT: So inside the while try this:
map.put(pairs.getKey(), pairs.getValue().add(number))
You are getting the error because you are trying to put an integer to the values, whereas it is expected an ArrayList
.
EDIT 2: Then put the following inside your while loop:
if(pairs.getKey().equals("mango")) { map.put(pairs.getKey(), pairs.getValue().add(18)); } else if(!map.containsKey("mango")) { List<Integer> ints = new ArrayList<Integer>(); ints.add(18); map.put("mango",ints); }
EDIT 3: By reading your requirements, I come to think you may not need a loop. You may want to only check if the map contains the key mango
, and if it does add 18
, else create a new entry in the map with key mango
and value 18
.
So all you may need is the following, without the loop:
if(map.containsKey("mango")) { map.put("mango", map.get("mango).add(18)); } else { List<Integer> ints = new ArrayList<Integer>(); ints.add(18); map.put("mango", ints); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With