如何使用Iterator遍历Map键集?
首先,创建一个要迭代的HashMap-
Map<String, String>map = new LinkedHashMap<>();
map.put("Jack","0");
map.put("Tim", "1");
map.put("David","2");
map.put("Tom", "3");
map.put("Kevin", "4");现在,使用Iterator通过键集进行映射-
Iterator iterator = map.keySet().iterator();
遍历所有对-
while (iterator.hasNext()) {
String resKey = (String) iterator.next();
System.out.println("Rank of " + resKey + " is " + map.get(resKey));
}示例
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class Demo {
public static void main(String[] args) {
Map<String, String>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("Katie","6");
map.put("Steve", "7");
map.put("Andrew", "8");
map.put("Angelina", "9");
String str = (String) map.get("David");
System.out.println("Rank of David = " + str);
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String resKey = (String) iterator.next();
System.out.println("Rank of " + resKey + " is " + map.get(resKey));
}
}
}输出结果
Rank of David = 2 Rank of Jack is 0 Rank of Tim is 1 Rank of David is 2 Rank of Tom is 3 Rank of Kevin is 4 Rank of Jeff is 5 Rank of Katies is 6 Rank of Steve is 7 Rank of Andrew is 8 Rank of Angelina is 9
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短