0

I want to print a nested HashMap which is :

HashMap<Integer,HashMap<Character,Integer>> map;

I searched a lot but I can't find a way to print the Integer because when I use getValues() on it, it tells me : "cannot find symbol". (Because it's an Integer value)

This is what I tried to do :

public void print(){
   for(Map.Entry<Integer, HashMap<Character,Integer>> t :this.map.entrySet()){
     Integer key = t.getKey();
     for (Map.Entry<Character,Integer> e : this.map.getValue().entrySet())
       System.out.println("OuterKey:" + key + " InnerKey: " + e.getKey()+ " VALUE:" +e.getValue());
   }
}

I can't use getValue() in my second for, so what else can I use ?

Thanks in advance ! Have a nice day. Chris.

ChrisBlp
  • 83
  • 1
  • 8

3 Answers3

6

getValue() is a method of Map.Entry, not Map.

You should use t.getValue().entrySet() instead of this.map.getValue().entrySet() in the second loop.

That would give you the inner Map.

public void print(){
   for(Map.Entry<Integer, HashMap<Character,Integer>> t :this.map.entrySet()){
     Integer key = t.getKey();
     for (Map.Entry<Character,Integer> e : t.getValue().entrySet())
       System.out.println("OuterKey:" + key + " InnerKey: " + e.getKey()+ " VALUE:" +e.getValue());
   }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
0

The easiest way to print the whole thing:

System.out.println(map.toString());

Yep, thats it; toString() returns a string ... that contains all the content of your Map; including its inner Map!

If you want to do that yourself, then you can use two loops:

for(Map.Entry<Integer, HashMap<Character,Integer>> innerMap : map.entrySet()) {
  for (Map.Entry<Character, Integer> aMap : innerMap.entrySet) {
    ... now you can call aMap.getKey() and .getValue()
GhostCat
  • 137,827
  • 25
  • 176
  • 248
0
public static void main(String[] args) {
        HashMap<Integer,HashMap<Character,Integer>> map = new HashMap<Integer,HashMap<Character,Integer>>();
        HashMap<Character,Integer> map1 = new HashMap<Character,Integer>();
        map1.put('1', 11);
        HashMap<Character,Integer> map2 = new HashMap<Character,Integer>();
        map2.put('2', 22);
        map.put(111, map1);
        map.put(222, map2);

        for (Integer temp : map.keySet()) {
            for (Character c : map.get(temp).keySet()) {
                System.out.println("key--" + c + "--value--" + map.get(temp).get(c));
            }
        }
    }

Hope it works.

Dale
  • 191
  • 1
  • 1
  • 12