Вопрос

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.

Это было полезно?

Решение

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" ] }

Другие советы

If you can use an immutable multimap, and don't need to mutate the multimap, then it's fairly simple:

new ImmutableListMultimap.Builder<Integer, String>
   .orderKeysBy(Ordering.natural())
   .putAll(multimap) // or put each entry
   .build();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top