按值对 HashMap 进行排序
当我需要按值对 HashMap 进行排序时,建议似乎是创建 HashMap,然后将数据放入按值排序的 TreeMap 中。
我的问题:为什么有必要这样做?为什么不创建一个 TreeMap(按键排序),然后按值对其进行排序?
When I need to sort a HashMap by value, the advice seems to be to create the HashMap and then put the data into a TreeMap which is sorted by value.
For example: Sort a Map<Key, Value> by values (Java)
My question: why is it necessary to do this? Why not create a TreeMap(which is sorted by keys) and then sort it in place by value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您知道自己的值是唯一的,则可以使用 Guava 的 BiMap(双向地图)来存储数据。像创建
HashMap
一样创建一个HashBiMap
,然后从其逆向创建一个新的TreeMap
:然后该映射将按值排序。请记住,您所认为的“键”和“值”将会被交换。
如果您的值不唯一,您可以创建逆多重映射。多重映射本质上是从每个键到一个或多个值的映射。它通常是通过制作从键到列表的映射来实现的。但你不必这样做,因为谷歌已经为你做了。只需从现有地图创建一个多重地图,然后让 Guava 为您将其反转为
TreeMultimap
,正如您所猜测的,它是一个可以容纳多个值的TreeMap
每个键。提供了 Multimap 文档。
If you know your values to be unique, you can use Guava's BiMap (bidirectional map) to store the data. Create a
HashBiMap
as you would yourHashMap
, then create a newTreeMap
from its inverse:That map will then be sorted by the values. Remember that what you're thinking of as "keys" and "values" will be swapped.
If your values are not unique, you can create a multimap of the inverse. A multimap is essentially a mapping from each key to one or more values. It's usually implemented by making a map from a key to a list. You don't have to do that though, because Google did it for you. Just create a multimap from your existing map, and ask Guava to invert it for you into a
TreeMultimap
, which, as you can guess, is aTreeMap
that can hold multiple values per key.Multimap documentation is provided.
因为您无法手动重新排序
TreeMap
的条目。 TreeMap 条目总是按键排序。我要扔掉 地图可以按照值的顺序迭代作为“如何做”的另一个答案,但是......具体来说,一个不返回令人窒息的地图的解决方案(通过抛出例外)对不在原始映射中的键进行查询。
Because you can't reorder the entries of a
TreeMap
manually. TreeMap entries are always sorted on the keys.I'm going to throw out Map that could be iterated in the order of values as another answer to "How to do it," though...specifically, a solution which doesn't return a map that chokes (by throwing exceptions) on queries to keys not in your original map.
我有这个非常小的代码,运行良好:
输出:
I have this very small code which is working fine:
Output:
我使用 Java 8 Stream API 编写了以下单行代码,以按值对任何给定映射进行排序:
I wrote the following one-liner using Java 8 Stream API to sort any given map by value: