如何使用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 教师闺蜜祝福语简短