Sorting the data in increasing order based on keys in Multimap Google Guava

血红的双手。 提交于 2019-12-06 03:30:46

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!