HashMap的遍历形式代码如下:
public class Solution {
public static void main(String[] args) {
HashMap<Integer, Integer> map = new HashMap<>();
map.put(1, 10);
map.put(2, 20);
map.put(3, 30);
map.put(4, 40);
//第一种keySet()方法
for (Integer key : map.keySet()) {
Integer v = map.get(key);
System.out.println(v);
}
//第二种entrySet()方法
for (var entry : map.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
//第三种forEach方法
map.forEach((k, v) -> {
System.out.println(k + ":" + v);
});
}
}
执行结果:
10 20 30 40
1:10
2:20
3:30
4:40
1:10
2:20
3:30
4:40
HashSet的遍历形式代码如下:
public class Solution {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
set.add(20);
set.add(30);
set.add(40);
set.add(50);
set.add(60);
//第一种,使用迭代器遍历
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
Integer n = it.next();
System.out.print(n + " ");
}
System.out.println();
//第二种使用增强for循环
for (Integer n : set) {
System.out.print(n + " ");
}
}
}
执行结果:
50 20 40 60 30
50 20 40 60 30