GNU Trove / trove4j TObjectIntHashMap is great for counting String occurences:
TObjectIntHashMap<Integer> map = new TObjectIntHashMap<>();
map.adjustOrPutValue(string, 1, 1);
Now a common task is to ask for the string with the highest count or iterate by decreasing count. How would you do this?
Thank you, Marcel
There are no special operations for this in TObjectIntHashMap
. To get the entry with max value, iterate through all entries:
class GetMaxEntry implements TObjectIntProcedure {
Object key;
int value = Integer.MIN_VALUE;
public boolean execute(Object k, int v) {
if (v >= value) {
key = k;
value = v;
}
return true;
}
}
GetMaxEntry getMaxEntry = new GetMaxEntry();
map.forEachEntry(getMaxEntry);
//process(getMaxEntry.key, getMaxEntry.value);
To iterate by decreasing count, the only thing you can do is to dump entries into a collection or array of, say, AbstractMap.SimpleImmutableEntry
s (or special Entry class with primitive value field) using the same forEachEntry
operation and then sort by Collections.sort()
or Arrays.sort()
with custom Comparator
.