简体   繁体   中英

Java edge case collection hashmap iteration

I got this problem I need to return the key in a hashmap with the largest value, the trick here is that the method must account for edge case scenarios. I can also only use the above imports, so Map.Entry is not allowed. Collections.sort isn't etc. Thanks.

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class Exercise {
    public static String findLargest(HashMap<String, Integer> map) {
        // Enter code here
 if(that.isEmpty()) return "";
        Integer maxInt = Integer.MIN_VALUE;
        String maxCity = "";
        for(String entry : that.keySet()) {
            if (that.get(entry) != null && that.get(entry) < Integer.MAX_VALUE && that.get(entry) > Integer.MIN_VALUE && that.get(entry) > maxInt) {
                maxInt = that.get(entry);
                maxCity = entry;
            }
        }
        return maxCity;
    }

    public static void check(String largest, List<String> apples, List<Integer> size) {
        HashMap<String, Integer> map = new HashMap<>();
        for (int i = 0; i < apples.size(); i++) {
            map.put(apples.get(i), size.get(i));
        }
        assert largest.equals(findLargest(map)) : "expected " + largest + " but was " + findLargest(map);
    }

    public static void main(String[] arg) {
        check("Granny", Arrays.asList("Granny", "Eve", "Rose"), Arrays.asList(5, 1, 2));
    }
}

The solution is really inefficient, but if you cannot add any other imports... it works. The first step is to find the maximum value among the integers and then for each of the keys, check if the map.get(key).equals(max) :

public static String findLargest(HashMap<String, Integer> map) {
    //step 1
    int max = Integer.MIN_VALUE;
    for (int i : map.values()) {
        max = Math.max(max, i);
    }
    //step 2        
    for (String str : map.keySet()) {
        if (map.get(str).equals(max)) {
            return str;
        }
    }
    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM