简体   繁体   English

如何对MultiMap进行排序 <k,v> 在java中?

[英]How do I sort a MultiMap<k,v> in java?

是否有理由在Java中对MultiMap进行排序,以及如何做到这一点?

Assuming you're talking about org.apache.commons.collections.MultiMap , then you can't; 假设您在谈论org.apache.commons.collections.MultiMap ,那么您不会; since it returns a Collection and not a List , it doesn't support the concept of order. 因为它返回一个Collection而不是一个List ,所以它不支持订单的概念。

If you are talking about org.apache.commons.collections.MultiHashMap , then all you need to do is iterate over the keys, take the ArrayList returned and sort it using Collections.sort() . 如果您正在谈论org.apache.commons.collections.MultiHashMap ,那么您要做的就是遍历键,获取返回的ArrayList并使用Collections.sort()对其进行排序。

That's assuming you are using that implementation though . 假设您正在使用该实现

There is nothing stopping you from implementing your own MultiMap fairly easily though, that supports sorting lists. 但是,没有什么可以阻止您相当轻松地实现自己的MultiMap ,因为它支持排序列表。 It may be as easy as HashMap<K, Collection<V>> , I'm not familiar with how MultiMaps work. 它可能像HashMap<K, Collection<V>>一样容易,我不熟悉MultiMaps的工作方式。

Actually I don't know why you would want to sort a Map. 实际上,我不知道您为什么要对地图进行排序。 A Map is a dictionary and you retrieve from this dictionary a (or in the case of multimaps a collection of) value(s) you're interested in. 地图是字典,您可以从该字典中检索您感兴趣的值(如果是多图,则为一个集合)。

In the case of a MultiMap you perhaps would want to sort the Collection resulting from a get. 在使用MultiMap的情况下,您可能希望对获取结果产生的Collection进行排序。 But what advantage do you have by a sorted Map since it doesn't speed up anything in finding a specific value? 但是,由于排序后的Map不会加快查找特定值的速度,因此您具有什么优势?

Easiest solution is to use TreeMultimap from guava. 最简单的解决方案是使用番石榴中的TreeMultimap。 Use either directly 直接使用

TreeMultimap<...> sortedMap = TreeMultimap.create(notSortedMultiMap);

if your keys and values are sortable naturally (implement Comparable), or 如果您的键和值是自然排序的(实现可比较),或者

TreeMultimap<...> sortedMap = TreeMultimap.create(keyComparator, valueComparator);
sortedMap.putAll(notSortedMultiMap);

if you need to provide custom comparators. 如果您需要提供自定义比较器。

If you know you will need it sorted and not care about retrieval speed that much, you can of course use TreeMap from very start. 如果您知道您需要对它进行排序并且不太在乎检索速度,那么您当然可以从一开始就使用TreeMap。

Then you can iterate over TreeMap or use something like values() or entries to get sorted collection. 然后,您可以遍历TreeMap或使用诸如values()或条目之类的东西来获取已排序的集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM