要使用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