The traversal form of HashSet and HashMap

The traversal form code of HashMap is as follows:

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);
        });
    }
}

Results of the:

10 20 30 40
1:10
2:20
3:30
4:40
1:10
2:20
3:30
4:40

The traversal form code of HashSet is as follows:

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 + " ");
        }
    }
}

Results of the:

50 20 40 60 30
50 20 40 60 30

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/112621506