简体   繁体   English

更改地图的迭代顺序

[英]Change iteration order for a Map

How can I iterate over a Map in a specific desired order? 如何以特定的期望顺序遍历Map? I currently have a HashMap and want to be able to define a specific iteration order. 我目前有一个HashMap,希望能够定义特定的迭代顺序。 The order should be able to get changed by the user. 用户应该可以更改订单。

My first thought was to use a LinkedHashMap since that one will give me an order of entries, but sadly the implementation only orders them by order of insertion or by order of access. 我的第一个想法是使用LinkedHashMap,因为那样会给我一个条目的顺序,但是可悲的是,实现仅按插入顺序或访问顺序对它们进行排序。 Other than manipulating the insertion order with deletes, I dont see the LinkedHashMap fit for the task. 除了用删除操作插入顺序外,我看不到LinkedHashMap适合该任务。 Imo the implementation kind of falls short of what the docs say about it. Imo的实现方式与文档中所说的不符。

I also found the SortedMap, but that one uses a comparator, so I needs to evaluate that every time I want to iterate over the entries. 我还找到了SortedMap,但是它使用了一个比较器,因此每次我要遍历条目时都需要对其进行评估。 This could be a solution, but is kind of expensive: O(n*log(n)). 这可能是一个解决方案,但很昂贵:O(n * log(n))。

So far Andreas comment seems to be the best solution, which is having both a HashMap and a ArrayList. 到目前为止,Andreas评论似乎是最好的解决方案,它同时具有HashMap和ArrayList。

Convert the LinkedHashMap to an ArrayList and then switch the value. 将LinkedHashMap转换为ArrayList,然后切换值。 Then convert back to LinkedHashMap. 然后转换回LinkedHashMap。 O(n) for both space and time complexity. 时空复杂度均为O(n)。

这个问题的正确答案是您使用了不正确的数据结构,因此必须重新排序。

如果您想要一个键值对,并且希望它具有ArrayList的属性,那么您可以尝试

List<Pair<String, String>> ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM