akglali
akglali

Reputation: 37

Get Each Element Of Array Value

I have an Hashmap

 private Map<String, int[]> aMap = new HashMap<String, int[]>();

Where I put multiple values inside of it

 aMap.put("3", new int[]{7, 14, 21, 28, 35, 42, 49, 57, 64, 71, 78, 85});
 aMap.put("5", new int[]{20, 39, 59, 79, 98, 118, 137, 157, 177, 196, 216, 236}) etc...

I need to reach every each element of array I used

for (String key : aMap.keySet()) {
  System.out.println("key : " + key);
  System.out.println("value : " + Arrays.toString(aMap.get(key)));
}

I can see arrays with that However I would like to access all elements inside of each element as an example I would like to get all these value separately 7, 14, 21, 28, 35, 42, 49, 57, 64, 71, 78, 85 and compare them with a value which I already calculated (we can name it as asValue).

Upvotes: 1

Views: 187

Answers (2)

Michal Krasny
Michal Krasny

Reputation: 5916

The value of the map is int[] (an array of int), you can iterate through every array to get its field like this:

for (Entry<String, int[]> entry : aMap.entrySet()) {
    System.out.println("key : " + entry.getKey());
    for (int i : entry.getValue()) {
        System.out.println("  array element: " + i);
    }
}

Also the first for loop should be working with Entry<String, int[]> rather than just Key, as you won't have to do the table lookup.

Upvotes: 4

Eritrean
Eritrean

Reputation: 16498

You can get the values of your map and store them in a local variable by something like

for (String key : aMap.keySet()) {
    System.out.println("key : " + key);
    int[] value = aMap.get(key);
    //do something with value array
}

Upvotes: 0

Related Questions