Unexpected output when trying to return key with largest value in LinkedHashMap java

68 Views Asked by At

Im trying to return the key with largest value in LinkedHashMap,

import java.util.LinkedHashMap;

public class stuff {
LinkedHashMap<Integer, Integer> hashMap = new LinkedHashMap<>();
static int maxKey;

  public void createHashmap() {
      hashMap.put(0,0);
      hashMap.put(2,3);
      }

    
  public int getHighestKey() {
      Integer maxKey = null;
      for (Integer key : hashMap.keySet()) {
          if (maxKey == null || hashMap.get(key) > hashMap.get(maxKey)) {
              maxKey = key;
          }
      }
      return maxKey;
  }

  public static void main(String[] args) {
      System.out.println(maxKey);
    
  }
}   

The output I get when I run this code is 0, even though in theory it should be 2. Why is this happening and how do I fix it.

2

There are 2 best solutions below

0
Bohemian On

You're comparing the map's values for the keys, not the keys themselves.

Change:

for (Integer key : hashMap.keySet()) {
    if (maxKey == null || hashMap.get(key) > hashMap.get(maxKey)) {
        maxKey = key;
    }
}

To

for (Integer key : hashMap.keySet()) {
    if (maxKey == null || key > maxKey) {
        maxKey = key;
    }
}

Rather than write your own code, you could have just done this:

Integer maxKey = Collections.max(hashMap.keySet());
0
WJS On

Here is yet another way.

  • first, check if the map exists and has values. Otherwise throw an exception since returing any default int could be misleading.
  • then just iterate over the keys, comparing current value to max.
 public int getHighestKey() {
     if(hashMap == null || hashMap.size() == 0) {
         throw new IllegalArgumentException("Map is null or empty");
     }
     int max = Integer.MIN_VALUE;
     for (int i : hashMap.keySet()) {
         max = Math.max(max, i);
     }
     return max;    
    }
}

Unless a LinkedHashMap is required, you could use a TreeMap which maintains the keys in a sorted order (ascending by default).

NavigableMap<Integer,Integer> map = new TreeMap<>();
map.put(7,8);
map.put(4,2);
map.put(5,2);

int maxKey = map.lastKey();
System.out.println(maxKey);

prints

7