import java.util.*; public class TopMultiMap extends TreeMap { private final int maxElems; private int minKey = Integer.MIN_VALUE + 1; private static Comparator topComp = new Comparator() { public int compare(Integer a, Integer b) { return a < b ? 1 : -1; } }; public TopMultiMap(int maxNumberElements) { super(topComp); maxElems = maxNumberElements; } @Override public V put(Integer key, V value) { if (key >= minKey) { super.put(key, value); int elemNum = 0; if (size() >= maxElems) for (Map.Entry entry : super.entrySet()) if (elemNum++ < maxElems) minKey = entry.getKey(); } return value; } @Override public Set> entrySet() { return headMap(minKey - 1).entrySet(); } public static void main(String[] args) { TreeMap islands = new TopMultiMap(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()); } }