In this article we will discuss how to search into a Map by value and fetch associated keys to the given value.

Suppose we have a map of string and integers i.e.

Now we want to get all the keys whose value is 2 i.e.  the &  at.  Let’s see How to do that,

Get Keys by Value in Map

To fetch the keys associated by given value, follow these steps,

  • First Check if given value exists in map using containsValue() function. If yes then,
  • Iterate over a given Map and for each Entry check if value matches the given value, if yes then store its key in the list.

Generic solution that will work with every map i.e. HashMap, TreeMap etc.

Complete example is as follows,




Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.