Find the Biggest number in HashSet/HashMap java

后端 未结 8 2207
我在风中等你
我在风中等你 2020-12-29 04:48

I would like to find the biggest number in HashSet and HashMap. Say I have the number [22,6763,32,42,33] in my HashSet and I want to find the largest number in my current Ha

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-29 05:18

    Here is a simple method which does what you are asking:

      public String getMapKeyWithHighestValue(HashMap map) {
        String keyWithHighestVal = "";
    
        // getting the maximum value in the Hashmap
        int maxValueInMap = (Collections.max(map.values()));
    
        //iterate through the map to get the key that corresponds to the maximum value in the Hashmap
        for (Map.Entry entry : map.entrySet()) {  // Iterate through hashmap
            if (entry.getValue() == maxValueInMap) {
    
                keyWithHighestVal = entry.getKey();     // this is the key which has the max value
            }
    
        }
        return keyWithHighestVal;
    }
    

提交回复
热议问题