如何使用 Java LinkedHashMap 保持插入顺序?


若要保持 LinkedHashMap 的插入顺序,请使用 Iterator。让我们首先创建一个 HashMap 并向其添加元素 -

LinkedHashMap<String, String>lHashMap = new LinkedHashMap<String, String>();
lHashMap.put("1", "A");
lHashMap.put("2", "B");
lHashMap.put("3", "C");
lHashMap.put("4", "D");
lHashMap.put("5", "E");
lHashMap.put("6", "F");
lHashMap.put("7", "G");
lHashMap.put("8", "H");
lHashMap.put("9", "I");

现在,使用 values() 方法获取值。遍历这些元素并显示它们 -

Collection collection = lHashMap.values();
Iterator i = collection.iterator();
while (i.hasNext()) {
   System.out.println(i.next());
}

示例

 在线演示

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
public class Demo {
   public static void main(String[] args) {
      LinkedHashMap<String, String>lHashMap = new LinkedHashMap<String, String>();
      lHashMap.put("1", "A");
      lHashMap.put("2", "B");
      lHashMap.put("3", "C");
      lHashMap.put("4", "D");
      lHashMap.put("5", "E");
      lHashMap.put("6", "F");
      lHashMap.put("7", "G");
      lHashMap.put("8", "H");
      lHashMap.put("9", "I");
      Collection collection = lHashMap.values();
      Iterator i = collection.iterator();
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }
}

输出

A
B
C
D
E
F
G
H
I

更新于:2019-7-30

159 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.