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,

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.