如何使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP