2

I have this variable :

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

I have the first(Integer) and the third element(Character) and I want to get the 2nd Integer with a function. How do i proceed ? I know how to get value from a normal Hashmap variable but i don't know how to do it with a nested hashmap...

I have already tried this :

import java.util.*;
public class Test{

  public static void main(String[] args){

   HashMap<Integer,HashMap<Integer,Character>> map;
   map = new HashMap<Integer,HashMap<Integer,Character>>();
   map.put(0,new HashMap<Integer,Character>());
   map.get(0).put(7,'c');

   System.out.println((map.get(0)).get('c'));
  }
}

I want to print 7 but this print gives me null.

Update : The best way to solve this problem is to change the structure. HashMap isn't designed to get the index from a value. However, there is a way (look below).

ChrisBlp
  • 83
  • 1
  • 8

1 Answers1

2

HashMap is not designed to obtain a key by a value, which is what you are trying to do with .get(c). It is designed to obtain a value for a given key.

It's possible you should change your data structure if you want efficient lookup.

Otherwise, you'll have to iterate over the inner Map's entries to locate a key having the requested value (there may be more than one such key).

For example :

HashMap<Integer,Character> inner = map.get(0);
Integer key = null;
if (inner != null) {
    for (Map.Entry<Integer,Character> entry : inner.entrySet()) {
        if (entry.getValue().equals('c')) {
            key = entry.getKey();
            break;
        }
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • You were totally right. I changed my data structure. Thanks for the code in case I want a little bit of challenge haha. – ChrisBlp Oct 31 '16 at 08:58