Wearybands
Wearybands

Reputation: 2455

Get the key and value of Map that is used Inside another Map (JAVA)

I am using a map inside another map, The key of the outer map is Integer and the value is another Map. I get the values as expected but I don't know how to get the key and value of teh inner map. Here is the code

Map<Integer, Map<Integer, Integer>> cellsMap = new HashMap<Integer, Map<Integer, Integer>>();
Map<Integer , Integer> bandForCell = cellsMap.get(band_number);
    if (bandForCell == null) 
        bandForCell = new HashMap<Integer, Integer>();
    bandForCell.put(erfcn, cell_found);
    cellsMap.put(band_number, bandForCell);

  csv.writeCells((Map<Integer, Map<Integer, Integer>>) cellsMap);

public void writeCells (Map<Integer, Map<Integer, Integer>> cellsMap ) throws IOException
{
    for (Map.Entry<Integer, Map<Integer, Integer>> entry : cellsMap.entrySet()) {
        System.out.println("Key: " + entry.getKey() + ". Value: " + entry.getValue() + "\n");
    }           
}

Out put of my Map

Key: 20 Value: {6331=0, 6330=1, 6329=1, 6328=0, 6335=1, 6437=0, 6436=1}

The value in the above output is another map. How can I get the key and value of the inner map from the value of the outer map?

Like Keys of inner map = 6331, 6330, 6329 .... and values of inner map = 0 , 1 , 1 , 0 ...

Thanks

Upvotes: 0

Views: 4579

Answers (2)

Wearybands
Wearybands

Reputation: 2455

This worked for me , Hope it will help someone else in future

 for (Map.Entry<Integer, Map<Integer, Integer>> outer : cellsMap.entrySet()) {
    System.out.println("Key: " + outer.getKey() +  "\n");
    for (Map.Entry<Integer, Integer> inner : entry.getValue().entrySet()) {
        System.out.println("Key = " + inner.getKey() + ", Value = " + inner.getValue());
    }
 }  

Upvotes: 2

mattdee123
mattdee123

Reputation: 213

In order to get a reference to an inner map, you would just use cellsMap.get(key). I'm not sure exactly what you want to do, but, for example, if you wanted to get the value where the first key was i and the second key was j, you could get it using cellsMap.get(i).get(j)

Or, if you wanted to print out all the keys and values of the inner map at index i, you could use

for (Map.Entry> entry : cellsMap.get(i).entrySet()) {
        System.out.println("Key: " + entry.getKey() + ". Value: " + entry.getValue() + "\n");
    }  

Upvotes: 0

Related Questions