title: How to Get All the Min Values from a Hash Map in Java
body: <p>I have a Hash Map with Keys objects of type Request and Values of type Integer. I use the following code to iterate through the map and get ALL the minimum values and then add their keys to a list. I emphasize to ALL because the keys are unique but the values can be duplicate, therefore there may be more than one map elements with the minimum value. </p>
  
  <p>However, this code gives me only a single such element, that is, the first that it finds through the iteration, even though I know there are more. For example, let us say that the map has the following requests - i.e. keys (I give the request IDs): 3 | 5 | 2 and their respective values are: 8 | 4 | 4. Thus, at this example we have two minimum elements, that is, two elements that share the minimum value, ID 5 and ID 2, both with value 4. The code will add to my list only the element with ID 5, that is, the first one of them. </p>
  
  <p>I have to note that there is a similar thread (<a href="https://stackoverflow.com/questions/10005053/key-for-maximum-value-in-hashtable">Key for maximum value in Hashtable</a>) but the provided solution does not work in my case. </p>
  
  <p>Here is the code:</p>
  
  <pre><code> Entry&lt;Request, Integer&gt; min = null;
  
   List&lt;Request&gt; minKeyList = new ArrayList&lt;Request&gt;();
  
   for(Entry&lt;Request, Integer&gt; entry : this.map.entrySet()) {
  
        if (min == null || min.getValue() &gt; map.getValue()) {
  
             min = entry;
             minKeyList.add(entry.getKey());
  
        }
  </code></pre>
  
  <p>Any suggestion or explanation why this is happenning would be appreciated. </p>
  
  <p>EDIT: New approach</p>
  
  <p>Well, I found a solution. It is not elegant, but it works. Here is the code.</p>
  
  <pre><code>    // list for finding the min value
      List&lt;Integer&gt; minValList = new ArrayList&lt;Integer&gt;();
  
      // List for keeping the keys of the elements with the min value
      List&lt;Request&gt; minKeyList = new ArrayList&lt;Request&gt;();
  
      // scan the map and put the values to the value list
      for(Entry&lt;Request, Integer&gt; entry : this.map.entrySet()) {
  
          minValList.add(entry.getValue());
  
      }
  
      // scan the map   
      for(Entry&lt;Request, Integer&gt; entry: this.map.entrySet()) {
  
          // find the min value
          if(entry.getValue() == Collections.min(minValList)) {
  
              // add the keys of the elements with the min value at the keyList
              minKeyList.add(entry.getKey());
  
         }
  
      }
  </code></pre>