How to get 5 highest values from a hashmap?

前端 未结 6 1110
慢半拍i
慢半拍i 2021-02-06 14:49

I have a Hashmap that links a zipcodes stored as keys and population stored as values in a hashmap.

The hashmap contains around 33k entries.

I\'m trying to get t

6条回答
  •  清歌不尽
    2021-02-06 15:17

    public class CheckHighiestValue { public static void main(String... s) {

        HashMap map = new HashMap();
    
        map.put("first", 10000);
        map.put("second", 20000);
        map.put("third", 300);
        map.put("fourth", 800012);
        map.put("fifth", 5000);
        map.put("sixth", 30012);
        map.put("seventh", 1234);
        map.put("eighth", 45321);
        map.put("nineth", 5678);
    
        Set> set = map.entrySet();
    
        List> list = new ArrayList>(
                set);
    
        Collections.sort(list, new Comparator>() {
    
            @Override
            public int compare(Entry o1,
                    Entry o2) {
    
                return o2.getValue().compareTo(o1.getValue());
            }
    
        });
        System.out.println(list.subList(0, 5));
    }
    

    }

提交回复
热议问题