如何使用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 婆婆高寿祝福语大全简短