I created a Multimap
Multimap<Integer, String> mhm= ArrayListMultimap.create();
my numbers range from 0 to 2400.
I have inserted data like
mhm.put(800 ,"A")
mhm.put(1200 ,"B")
mhm.put(1200 ,"A")
mhm.put(1500 ,"B")
mhm.put(600 ,"A")
mhm.put(700 ,"B")
mhm.put(1200 ,"A")
mhm.put(1201 ,"B")
I want to sort the Multimap on key field that is Integer? There are not much posts on satckoverflow which tells how to do this.
expected output:
mhm.put(600 ,"A")
mhm.put(700 ,"B")
mhm.put(800 ,"A")
mhm.put(1200 ,"B")
mhm.put(1200 ,"A")
mhm.put(1200 ,"A")
mhm.put(1201 ,"A")
mhm.put(1500 ,"B")
Please note that the expected output is sorted only on key. If two keys have same value then the key which appeared first should come first. how to enforce this? Is this case automatically taken care when we sort the Multimap on keys?
This is not homework question, trying to play around Google Guava.
If you can use an immutable multimap, and don't need to mutate the multimap, then it's fairly simple:
You want keys in natural order - just use custom
Multimap
usingnewListMultimap
fromMultimaps
class:In Java 8 it's shorter:
But if you're using Guava 16+ (and you should now), you can use
MultimapBuilder
which is even more clean: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: