如何使用 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
廣告