Q:

remove smallest k elements from hashmap in JAVA

I have a hashmap of objects. Each object has two attributes (let say int length and int weight).
I want to remove k elements with the smallest length.
What is the efficient way of doing this?

A:

Map<K, V> map = new HashMap<>();

...

Set<K> keys = map.keySet();
TreeSet<K> smallest = new TreeSet<>(new Comparator<K>(){
    public int compare(K o1, K o2) {
        return o1.getLength() - o2.getLength();
    }
});
smallest.addAll(keys);
for(int x = 0; x < num; x++) {
    keys.remove(smallest.pollFirst());
}

Where K is your key type, V is your value type, and num is the number of elements you wish to remove.
If you are doing this frequently, it might be a good idea to use a TreeMap in the first place.

