如何使用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
热门推荐
10 给儿子祝福语简短霸气
11 生日祝福语古朴简短独特
12 鼓励孩子小考祝福语简短
13 前程祝福语简短暖心
14 学霸毕业祝福语简短
15 鼠年新年贺卡祝福语简短
16 祝女人美丽祝福语简短
17 新年探亲祝福语简短精辟
18 新婚红包祝福语简短男