维护HashMap中的顺序 [英] Maintaining order in HashMap

查看:118
本文介绍了维护HashMap中的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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 ?

考虑给定的代码:

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 

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

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

E F A B C D


推荐答案

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

HashMap itself doesn't maintain insertion order - but LinkedHashMap does, so use that instead.

如记录所示...... HashMap

As documented... 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.

LinkedHashMap


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

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).

这篇关于维护HashMap中的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆