import java.util.*; public class TopMap extends TreeMap { private final int maxElems; public TopMap(int maxNumberElements) { super(Collections.reverseOrder()); maxElems = maxNumberElements; } @Override public V put(Integer key, V value) { //while (containsKey(key)) key = key + 1; //optional hack if (size() < maxElems || key > lastKey()) super.put(key, value); if (size() > maxElems) remove(lastKey()); return value; } public static void main(String[] args) { TreeMap islands = new TopMap(3); islands.put( 507000, "Baffin"); islands.put( 726000, "Borneo"); islands.put(2131000, "Greenland"); islands.put( 578000, "Madagascar"); islands.put( 800000, "New Guinea"); System.out.println("Three Largest Islands:"); for (Map.Entry island : islands.entrySet()) System.out.println(island.getKey() + " sq km - " + island.getValue()); } }