按值的字母顺序对 HashMap 进行排序
我有一个 HashMap
,其中 Object 是学生的 ID,Student 是来自 Student 的对象。
如何通过学生姓名 student->getName()
重新调用 HashMap?
I have a HashMap<Object, Student>
where the Object is the ID of the Student, and the Student is an object from Student.
How can I resort the HashMap by the Students name, student->getName()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
HashMap 本质上是无序的,无法排序。
相反,您可以使用 SortedMap 实现,例如 TreeMap。
然而,即使是排序的映射也只能按其键进行排序。
如果您想按值排序,则需要将它们复制到排序列表中。
HashMaps are intrinsically unordered and cannot be sorted.
Instead, you can use a SortedMap implementation, such as a TreeMap.
However, even a sorted map can only sort by its keys.
If you want to sort by the values, you'll need to copy them to a sorted list.
您可能无法对 HashMap 进行排序,但您当然可以做一些提供相同效果的事情。我能够对 HashMap进行排序通过使用 Java 重访 博客。同样的原则也适用于 HashMap。 object:
要调用此方法,我使用:
阅读更多内容:http://javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html#ixzz2akXStsGj
You might not be able to sort a HashMap, but you can certainly do something that provides the same effect. I was able to sort my HashMap <String, Integer> by descending value of the Integer by using the excellent code posted at the Javarevisited blog. The same principle would apply to a HashMap <String, String> object:
To call this method, I use:
Read more: http://javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html#ixzz2akXStsGj
地图不能按值排序。不过,您可以这样做:
当然,假设您需要迭代这些值。 (不然你为什么要这样订购呢?)
祝你好运。
Maps cannot be ordered by values. You can do this, though:
Assuming, of course, that you need to iterate over the values. (Why else would you want it ordered like that?)
Good luck.
HashMap 不能按其值排序。 Map 设计用于基于键的恒定时间查找,因此不需要按值排序。如果您需要按名称排序,我建议使用
SortedSet
并创建一个按名称排序的比较器。如果您同时需要恒定时间查找和按值排序的集合,那么您可能需要维护映射和集合。
HashMaps cannot be sorted by their values. A Map is designed for constant time lookups based on the key, so ordering by values should not be necessary. If you need to sort by name, I suggest using a
SortedSet
and creating a comparator that sorts by the names.If you need both a constant time lookup and a sorted-by-value set, then you may need to maintain a map and a set.
我肯定会使用一个新类来存储密钥和对象。
然后你可以将Map的每个元素以此类的形式放入一个ArrayList中,最后使用比较器对ArrayList进行排序,然后你只需构建一个新的Map即可。代码将是这样的:
PairValue 类
这就是我解决过去遇到的一些类似问题的方法。请注意,返回的映射实现需要是 LinkedHashMap。
I would definitely use a New Class that will store the key and the Object.
Then you can put every element of the Map into an ArrayList in the form of this class, and finally use a comparator to sort the ArrayList, afterwards you simply build a new Map. Code will be something like this:
The PairValue class
Thats the way I solved some similar problem I had in the past. Please Note that the returned map implementation needs to be a LinkedHashMap.