How to get 5 highest values from a hashmap?

前端 未结 6 1105
慢半拍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:16

    This is something i made and hopefully provides you something that you want to use.

    public class TopsCollection { 
    
    private static Map collectors = new HashMap<>();
    
    public TopsCollection() {
    }
    
    public void add(String playerName, int score) {
        collectors.put(playerName, score);
    }
    
    public void clearCollectors() {
        synchronized (collectors) {
            collectors.clear();
        }
    }
    
    public List> getTops() {
        return collectors.entrySet().stream().sorted(comparing(Map.Entry::getValue, reverseOrder())).limit(5).collect(toList());
    }
    
    public int getTopByName(String name) {
        for (int i = 0; i < getTops().size(); i++) {
            if (getTops().get(i).getKey().contains(name)) {
                return i;
            }
        }
        return 0;
    }
    

    getTopByName allows you to get the top place of the specified name.

提交回复
热议问题