Java 在 HashMap 中维护顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19164699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:39:30  来源:igfitidea点击:

Maintaining order in HashMap

java

提问by OneMoreError

I have a list which I convert to a map to do some work. After that, i convert the map back again to a list, but this time the order is random. I need the same initial order retained in my second list.

我有一个列表,我将其转换为地图来做一些工作。之后,我再次将地图转换回列表,但这次顺序是随机的。我需要在我的第二个列表中保留相同的初始订单。

the obvious reason is that a HashMap doesn't maintain order. But I need to do something so that it does. I cannot change the Map implementation.How can I do that ?

显而易见的原因是 HashMap 不维护顺序。但我需要做一些事情才能做到。我无法更改 Map 实现。我该怎么做?

Consider the given code:

考虑给定的代码:

import java.util.*;
public class Dummy {

public static void main(String[] args) {
    System.out.println("Hello world !");
    List<String> list = new ArrayList<String>();
    list.add("A");list.add("B");list.add("C");
    list.add("D");list.add("E");list.add("F");

    Map<String,String> map = new HashMap<String, String>();

    for(int i=0;i<list.size();i=i+2)
        map.put(list.get(i),list.get(i+1));

    // Use map here to do some work

    List<String> l= new ArrayList<String>();
    for (Map.Entry e : map.entrySet()) {
        l.add((String) e.getKey());
        l.add((String) e.getValue());
    }
  }
}

For ex - Initially, when I printed the list elements, it printed out

例如 - 最初,当我打印列表元素时,它打印出来

A B C D E F 

Now, when I print the elements of List l, it printed out

现在,当我打印 的元素时List l,它打印出来

E F A B C D

采纳答案by Jon Skeet

HashMapitself doesn't maintain insertion order - but LinkedHashMapdoes, so use that instead.

HashMap本身不维护插入顺序 - 但LinkedHashMap确实如此,因此请改用它。

As documented... HashMap:

正如记录的那样...... HashMap

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

此类不保证地图的顺序;特别是,它不保证订单会随着时间的推移保持不变。

And LinkedHashMap:

并且LinkedHashMap

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

Map接口的哈希表和链表实现,迭代顺序可预测。此实现与 HashMap 的不同之处在于它维护一个双向链表,贯穿其所有条目。这个链表定义了迭代顺序,这通常是键被插入到映射中的顺序(插入顺序)。

回答by Jigar Joshi

HashMapdoesn't preserve order of insertion

HashMap不保留插入顺序

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Map接口的基于哈希表的实现。此实现提供所有可选的映射操作,并允许空值和空键。(HashMap 类大致等同于 Hashtable,只是它是非同步的并且允许空值。)该类不保证映射的顺序;特别是,它不保证订单会随着时间的推移保持不变。

Use LinkedHashMapif you want to preserve order of keys

LinkedHashMap如果要保留键的顺序,请使用

回答by Kayaman

Why can't you change the Mapimplementation (to LinkedHashMapfor example)?

为什么你不能改变Map实现(LinkedHashMap例如)?

If there's a logical ordering, you could sort the List with a custom Comparator.

如果有逻辑顺序,您可以使用自定义Comparator.

回答by DT7

Use LinkedHashMapinstead of HashMap to maintain order.

使用LinkedHashMap而不是 HashMap 来维护顺序。

Map<String,String> map = new LinkedHashMap<String, String>();

回答by Drifter64

Consider making your items sortable. In the case of strings, there is already a natural ordering; alphabetical. You can make objects that use the sortable class, and therefore you can use sorting algorithms to put these objects in a nice order, no matter what order you get them in from hash!

考虑使您的项目可排序。在字符串的情况下,已经有一个自然排序;按字母顺序。您可以创建使用 sortable 类的对象,因此您可以使用排序算法将这些对象按良好的顺序排列,无论您从哈希中获取它们的顺序如何!

回答by Hyman

It's time for a LinkedHashMap, it is meant exactly to preserve insertion order.

是时候使用 a 了LinkedHashMap,它的目的是保留插入顺序。

Mind that even a TreeMapexists, which allows you to keep your desired order by using Comparable interface. It is not an hash map anymore, but a tree.

请注意,即使TreeMap存在,也允许您通过使用 Comparable 接口保持所需的顺序。它不再是哈希映射,而是一棵树。

回答by David Conrad

If you truly are unable to switch to another Mapimplementation (LinkedHashMapis exactlywhat you want), then the only other possibility is to retain the original List,and use it to create the new Listfrom the Map.

如果你真的无法切换到另一个Map实现(LinkedHashMap正是你想要的),那么唯一的另一种可能性是保留原来的List,,并用它来创建新的ListMap.

public <T> List<T> listFromMapInOrder(final Map<T, T> map, final List<T> order) {
    List<T> result = new ArrayList<T>();
    for (T key : order) {
        if (map.containsKey(key)) {
            result.add(key);
            result.add(map.get(key));
        }
    }
    return result;
}

But I would refactor the code until it was possible to switch to a LinkedHashMap.

但我会重构代码,直到可以切换到 LinkedHashMap.