Search code examples
javasearchnestedhashmaptreemap

How should I search items in a nested HashMap with inner key?


I have a nested HashMap HashMap<String, TreeMap<Integer, Item>>, and now I know the inner key Id(Integer) in TreeMap but don't have the key String in HashMap. Could I use some build-in methods or something else without iterating the HashMap to get what I want?

Previously, if I know the key String, I can use HashMap.get(String key)to get the item, and then use TreeMap.get(Integer inner_key), but I don't know what to do now if I don't have the outside key. Is it iterating the HashMap the only way?


Solution

  • "... Could I use some build-in methods or something else without iterating the HashMap to get what I want? ..."

    Unfortunately not.  Although, an iteration is only a few lines.

    String key(int i, HashMap<String, TreeMap<Integer, Item>> map) {
        for (Map.Entry<String, TreeMap<Integer, Item>> e : map.entrySet())
            if (e.getValue().containsKey(i)) return e.getKey();
        return null;
    }
    

    Alternately, use a stream.

    String key(int i, HashMap<String, TreeMap<Integer, Item>> map) {
        return map.entrySet()
                  .stream()
                  .filter(x -> x.getValue().containsKey(i))
                  .findFirst()
                  .get().getKey();
    }