如何使用 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 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告