如何使用Java集合跟踪插入顺序?
要跟踪插入顺序,如果是Map,则可以使用Map.Entry()。假设我们有以下LinkedHashMap-
Map<String, Integer>map = new LinkedHashMap<>();
map.put("Jack", 0);
map.put("Tim", 1);
map.put("David", 2);
map.put("Tom", 3);
map.put("Kevin", 4);
map.put("Jeff", 5);现在,遍历Map.Entry并使用Key和Value正确获取插入顺序-
for (Map.Entry<String, Integer>entry: map.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}示例
import java.util.LinkedHashMap;
import java.util.Map;
public class Demo {
public static void main(String[] args) {
Map<String, Integer>map = new LinkedHashMap<>();
map.put("Jack", 0);
map.put("Tim", 1);
map.put("David", 2);
map.put("Tom", 3);
map.put("Kevin", 4);
map.put("Jeff", 5);
map.put("Katies", 6);
map.put("Steve", 7);
map.put("Andrew", 8);
map.put("Angelina", 9);
for (Map.Entry<String, Integer>entry: map.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
}
}输出结果
Jack => 0 Tim => 1 David => 2 Tom => 3 Kevin => 4 Jeff => 5 Katies => 6 Steve => 7 Andrew => 8 Angelina => 9
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西