简体   繁体   中英

Java - Fetch key from HashMap Single Key Multiple Values (Reverse Map)

I have a HashMap defined with something like this:

Map<Foo, List<Bar>> = new HashMap();

I am trying to do a reverse search of the Hashmap using the Bar to get the Foo .

I am wanting to do something like this:

if(ArrayListBar.contains(bar)) {
    return Foo;
} else {
    return null;
}

Is this achievable in HashMap or is there a better way to deal with this without using the HashMap?

You can do it with Map iteration.

private Foo getKeyByValue(Map<Foo, List<Bar>> map, Bar bar){
    for (Map.Entry<Foo, List<Bar>> entry : map.entrySet()){
        if (entry.getValue().contains(bar)){
            return entry.getKey();
        }
    } 
  return null;
}

You iterate for each entry on the map and you return the Key when the array list contains the entered bar value.

Note that your Bar class should implement the equals method so the entry.getValue().contains(bar) can be evaluated if the bar in the List with the bar on the method input are different objects.

Update: Added missing return null statement when no map element is found.

The best approach can be different under different circumstances.

You can do it by iterating the map and checking whether the list of each entry contains the value or not. But that's Ok only if the map is not too big and the lists in it or either not too big or sorted.

But if the size of the map is big or the lists are big and not sorted and you need to do multiple lookups, it is better to create a reverse map Map. In that case you have to make sure the hashkey and equals method of Bar are implemented correctly. If the same value (Bar) can be in multiple lists for different keys (Foo), the reverse map might also require a list of values: Map>.

Depending on the situation, you can create the reverse map while building the original map or afterwards when doing the first lookup and cache it for reuse in later lookups. When thread safety is involved, it is preferred to create it when creating the original map because in that case you don't need to worry about thread safety of the lookup method which is a problem when creating the reverse map during the first lookup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM