在 Java 中:获取按映射键排序的映射值数组
我有一个哈希映射,我希望获取此哈希映射中的值的数组,但我希望该数组按哈希映射中的键进行排序。
例如,如果地图如下所示:
- <2,obj1>
- <4,obj2>
- <0,obj3>
- <10,obj4>
- <5,obj5>
- <1,obj6>
- <15,obj7>
- <3,obj8>
我希望数组为: [obj3,obj6,obj1,obj8,obj2,obj5,obj4,obj7]
越快越好。有内置的方法可以做到这一点吗?
I have a hashmap, I wish to get an array of the values in this hashmap, but I wish for the array to be sorted by the keys in the hashmap.
For instance if the map looks like this:
- <2,obj1>
- <4,obj2>
- <0,obj3>
- <10,obj4>
- <5,obj5>
- <1,obj6>
- <15,obj7>
- <3,obj8>
I want the array to be: [obj3,obj6,obj1,obj8,obj2,obj5,obj4,obj7]
The faster the better. Is there a built in way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您想要一个
SortedMap
,特别是TreeMap
。您可以利用映射维护键的排序列表来生成输出数组,例如通过使用SortedMap.values()
或迭代映射中的条目。Sounds like you want a
SortedMap
, specifically aTreeMap
. You can use the fact that the map maintains a sorted list of keys to generate your output array, e.g. by usingSortedMap.values()
or by iterating over the entries in the map.我总是喜欢能够以通过单元测试的形式回答:
I always like when I can answer in the form of a passing unit test: