本文介绍了根据Multimap Google Guava中的键,按递增顺序对数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我创建了一个Multimap I created a Multimap Multimap<Integer, String> mhm= ArrayListMultimap.create();我的数字范围从0到2400。my numbers range from 0 to 2400.我已插入数据,如 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")我想在关键字段Integer上对Multimap进行排序? satckoverflow上没有太多帖子告诉你如何做到这一点。 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. 预期产出: 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")请注意,预期输出仅按键排序。 如果两个键具有相同的值,那么首先出现的键应该首先出现。 如何执行此操作?我们在按键上对Multimap进行排序时会自动注意这种情况吗?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? 这不是功课问题,试图玩Google Guava。 推荐答案你想要自然顺序的键 - 只需使用自定义 Multimap 使用 Multimaps class :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(); } });在Java 8中它更短:In Java 8 it's shorter:ListMultimap<Integer, String> mhm = Multimaps.newListMultimap( new TreeMap<>(), ArrayList::new);但如果您使用的是Guava 16+(现在就应该使用),您可以使用 MultimapBuilder 更干净: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();因为您可以将multimap视为地图密钥 - >集合,只需使用JDK的 TreeMap 根据其键的自然顺序进行排序。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.示例:mhm.put(2, "some");mhm.put(1, "value");mhm.put(2, "here");System.out.println(mhm.toString());// { 1: [ "value" ], 2: [ "some", "here" ] } 这篇关于根据Multimap Google Guava中的键,按递增顺序对数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 22:20