3

我使用 Guava MultiMap (impl LinkedListMultimap) 允许我为一个键存储多个值,但是我想按最大值对映射进行排序并返回键。

IE

第一次运行后我有

key1:{13}
key2:{7}
key3:{11}

第二次运行后,我现在有了

key1:{13,14}
key2:{7,18}
key3:{11,1}

第三次运行后,我现在有了

key1:{13,14,16}
key2:{7,18,6}
key3:{11,1,22}

我想要一个订单

key3
key2
key1

我想输出键(我不再需要知道值)

我想不出办法,我不必使用 MultiMap 它看起来可能会有所帮助

4

2 回答 2

5

如果我是你,我会从不使用 a 开始Multimap,而是使用 aMap来跟踪与每个键关联的最大值。然后,你有一个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());

解压一下:

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
于 2012-10-18T17:24:28.213 回答
2

我要做的是将 entrySet 粘贴到带有自定义比较器的 TreeSet 中。然后拔出钥匙。

sortedEntries = Sets.newTreeSet(comparator).addAll(multimap.entries());
return Collections2.transform(sortedEntries, keyExtractor);

keyExtractor、比较器和参数化的实现留给读者作为练习。

于 2012-10-19T05:26:16.767 回答