Generic method to sort a map by value and then return the top k keys - Java java.util

Java examples for java.util:Map Key

Description

Generic method to sort a map by value and then return the top k keys

Demo Code


import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Main{
    /**/*www  .  j a  v a  2s.c o m*/
     * Generic method to sort a map by value and then return the top k keys
     * @param <K>
     * @param <V>
     * @param map
     * @param k
     * @return
     */
    public static <K, V extends Comparable<V>> List<K> sortMapLimitToList(
            Map<K, V> map, int k, boolean keepHighest) {
        List<Entry<K, V>> sorted = sortByValue(map);
        if (keepHighest)
            Collections.reverse(sorted);
        List<K> res = new ArrayList<K>();
        int count = 0;
        for (Map.Entry<K, V> e : sorted) {
            if (count >= k)
                break;
            else
                res.add(e.getKey());
            count++;
        }
        return res;
    }
    /**
     * Generic method to sort a map by value
     * @param <K>
     * @param <V>
     * @param map
     * @return
     */
    public static <K, V extends Comparable<V>> List<Entry<K, V>> sortByValue(
            Map<K, V> map) {
        List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>(
                map.entrySet());
        Collections.sort(entries, new ByValue<K, V>());
        return entries;
    }
}

Related Tutorials