sclass OptimizedMultiSet { new Map map; // outer tree map for sorting // inner linked hash set for reproducability (HashSet ordering sucks) transient MultiSetMap byCount = multiSetMap_innerLinkedHashSet_outerRevTreeMap(); int size; int add(A a) { ret add(a, 1); } int add(A a, int count) { if (count <= 0) ret 0; size += count; Int i = map.get(a); if (i != null) byCount.remove(i += count, a); else i = count; map.put(a, i); byCount.add(i, a); ret i; } void remove(A a) { Int i = map.get(a); if (i != null) { --size; byCount.remove(i, a); if (--i > 0) { map.put(a, i); byCount.add(i, a); } else map.remove(a); } } bool isEmpty() { ret map.isEmpty(); } toString { ret str(map); } A getMostPopularEntry() { ret firstValue(byCount); } void _doneLoading { rebuildByCount(); } // internal void rebuildByCount { byCount.clear(); for (A entry, int count : map) byCount.put(count, entry); } int get(A a) { ret map.get(a); } int size() { ret size; } }