How to get 5 highest values from a hashmap?

前端 未结 6 1107
慢半拍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 14:58

    Putting the entries of such a set into a list and sorting it is one option. But 33k elements is a number where the O(n*log(n)) complexity of sorting might already have a noticable performance impact.

    One apporach would be to employ the PriorityQueue that nr4bt already mentioned (I wrote this snippet while he answered). It basically inserts all elements into a PriorityQueue that is sorted according to the values of the map entries.

    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.PriorityQueue;
    
    public class GreatestOfMap
    {
        public static void main(String[] args)
        {
            Map map = new HashMap();
    
            map.put("zip000", 1234);
            map.put("zip001", 2345);
            map.put("zip002", 3456);
            map.put("zip003", 4567);
            map.put("zip004", 5678);
            map.put("zip005", 6789);
            map.put("zip006", 123);
            map.put("zip007", 234);
            map.put("zip008", 456);
            map.put("zip009", 567);
            map.put("zip010", 7890);
            map.put("zip011", 678);
            map.put("zip012", 789);
            map.put("zip013", 890);
    
            int n = 5;
            List> greatest = findGreatest(map, 5);
            System.out.println("Top "+n+" entries:");
            for (Entry entry : greatest)
            {
                System.out.println(entry);
            }
        }
    
        private static > List> 
            findGreatest(Map map, int n)
        {
            Comparator> comparator = 
                new Comparator>()
            {
                @Override
                public int compare(Entry e0, Entry e1)
                {
                    V v0 = e0.getValue();
                    V v1 = e1.getValue();
                    return v0.compareTo(v1);
                }
            };
            PriorityQueue> highest = 
                new PriorityQueue>(n, comparator);
            for (Entry entry : map.entrySet())
            {
                highest.offer(entry);
                while (highest.size() > n)
                {
                    highest.poll();
                }
            }
    
            List> result = new ArrayList>();
            while (highest.size() > 0)
            {
                result.add(highest.poll());
            }
            return result;
        }
    }
    

提交回复
热议问题