Pau*_*lor 3 java sorting multimap guava
我使用Guava MultiMap(impl LinkedListMultimap)来允许我为一个键存储多个值,但后来我想按最高值对地图进行排序并返回键.
即
第一次运行后,我有
key1:{13}
key2:{7}
key3:{11}
Run Code Online (Sandbox Code Playgroud)
第二次运行后,我现在有了
key1:{13,14}
key2:{7,18}
key3:{11,1}
Run Code Online (Sandbox Code Playgroud)
第三次运行后,我现在有了
key1:{13,14,16}
key2:{7,18,6}
key3:{11,1,22}
Run Code Online (Sandbox Code Playgroud)
我想订购
key3
key2
key1
Run Code Online (Sandbox Code Playgroud)
我想输出键(我不再需要知道值)
我不能找到一种方法来做到这一点,我不必使用MultiMap,它看起来可能会有所帮助
如果我是你,我首先不使用a Multimap,而是使用a Map来跟踪与每个键相关的最大值.然后,你有一个Map<String, Integer>,如果你Map之后不需要保存,那么我会做类似的事情
final Map<String, Integer> map = ...
return Ordering.natural().onResultOf(Functions.forMap(map)).reverse()
// a comparator to compare strings in descending order of their
// associated values
.immutableSortedCopy(map.keySet());
Run Code Online (Sandbox Code Playgroud)
打开包装:
Ordering.natural() // the natural ordering on integers
.onResultOf(
Functions.forMap(map) // use the Map<String, Integer> as a Function
// this ordering now compares Strings by the natural ordering of
// the integers they're mapped to
.reverse(); // reverses the ordering, so it now sorts in descending order
Run Code Online (Sandbox Code Playgroud)