Finding the n largest values in a hashmap

This question already has an answer here:

  • Iterate through a HashMap [duplicate] 7 answers

  • Probably this is not the most efficient way to do, but it should solve your problem:

    static HashMap<String, Integer> nLargest(HashMap<String, Integer> map, int n) { //map and n largest values to search for
    
        Integer value;
        ArrayList<String> keys = new ArrayList<>(n); //to store keys of the n largest values
        ArrayList<Integer> values = new ArrayList<>(n); //to store n largest values (same index as keys)
        int index;
        for (String key : map.keySet()) { //iterate on all the keys (i.e. on all the values)
            value = map.get(key); //get the corresponding value
            index = keys.size() - 1; //initialize to search the right place to insert (in a sorted order) current value within the n largest values
            while (index >= 0 && value > values.get(index)) { //we traverse the array of largest values from smallest to biggest
                index--; //until we found the right place to insert the current value
            }
            index = index + 1; //adapt the index (come back by one)
            values.add(index, value); //insert the current value in the right place
            keys.add(index, key); //and also the corresponding key
            if (values.size() > n) { //if we have already found enough number of largest values
                values.remove(n); //we remove the last largest value (i.e. the smallest within the largest)
                keys.remove(n); //actually we store at most n+1 largest values and therefore we can discard just the last one (smallest)
            }
        }
        HashMap<String, Integer> result = new HashMap<>(values.size());
        for (int i = 0; i < values.size(); i++) { //copy keys and value into an HashMap
            result.put(keys.get(i), values.get(i));
        }
        return result;
    }
    

    I hope this will help you.

    链接地址: http://www.djcxy.com/p/17984.html

    上一篇: 调用集合中每个对象的方法的最佳方法

    下一篇: 在hashmap中查找n个最大值