2

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

leventov
  • 14,760
  • 11
  • 69
  • 98
dreamflasher
  • 1,387
  • 15
  • 22

2 Answers2

2

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.SimpleImmutableEntrys (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.

leventov
  • 14,760
  • 11
  • 69
  • 98
  • Thank you leventov, yeah I feared this is the only way, but this would require to create a copy of the map so one loses the performance there again. – dreamflasher Apr 09 '14 at 23:42
1

As @leventov said, you'd currently need to iterator through the entire collection as sorted collections don't currently exist in Trove. There is a feature request here that you could vote on if this is interesting to you.

Rob Eden
  • 362
  • 2
  • 7