You want keys in natural order - just use custom Multimap
using newListMultimap
from Multimaps
class:
ListMultimap<Integer, String> mhm = Multimaps.newListMultimap(
new TreeMap<Integer, Collection<String>>(),
new Supplier<List<String>>() {
public List<String> get() {
return Lists.newArrayList();
}
});
In Java 8 it's shorter:
ListMultimap<Integer, String> mhm = Multimaps.newListMultimap(
new TreeMap<>(), ArrayList::new);
But if you're using Guava 16+ (and you should now), you can use MultimapBuilder
which is even more clean:
ListMultimap<Integer, String> mhm = MultimapBuilder.treeKeys().arrayListValues().build();
Because you can think of multimap as map key -> collection, just use JDK's TreeMap
which is sorted according to the natural ordering of its keys.
Example:
mhm.put(2, "some");
mhm.put(1, "value");
mhm.put(2, "here");
System.out.println(mhm.toString());
// { 1: [ "value" ], 2: [ "some", "here" ] }