I have a hashmap where the keys are strings and the values are integers.

I want to make a method to get the key of the 2nd smallest integer value, and if there are multiple keys, to return -1.

I have no idea where to start. Can someone please help me make this method??

1 Answers

user10888593 On

give some ideas but not the best.

You can do like this:

public static Object getSecondMinValue(Map map) {
    if (map == null) return null;
    Collection c = map.values();
    Object[] obj = c.toArray();
    return obj[1];

public static Object getKey(HashMap map, String v) {
    String key = "";
    for (Map.Entry m : map.entrySet()) {
        if (m.getValue().equals(v)) {
            key = m.getKey();
    return key;