I would like to have a c.g.c.c.Multimap
that is sorted based on keys only. The values shouldn\'t be sorted. I\'ve tried to build something with guava\'s T
How about this:
public static Multimap<Integer, MyObject> indexOnScore(Iterable<MyObject> i) {
Multimap<Integer, MyObject> m = Multimaps.index(i, myObjectToScore());
Multimap<Integer, MyObject> sortedKeys = Multimaps.newMultimap(
Maps.<Integer, Collection<MyObject>>newTreeMap(),
new Supplier<Collection<MyObject>>() {
@Override
public Collection<MyObject> get() {
return Lists.newArrayList(); // Or a Set if appropriate
}
}
);
sortedKeys.putAll(m);
return sortedKeys;
}
There would be the overhead of creating two separate Multimap
s in this case, though.
You can do it with TreeMultimap if you use Comparators.
Create a Comparator for the key type and the value type (MyObject
?). Then use create(Comparator keyComparator, Comparator valueComparator) to make the map.
The benefit of using a Comparator over implementing Comparable is that you can make the Comparator specific to the situation that you want with the map and it doesn't effect your object in general. As long as your Comparator is consistent with equals it can do whatever you want.