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.
You're comparing the map's values for the keys, not the keys themselves.
Change:
To
Rather than write your own code, you could have just done this: