HashMap 순회에 가장 일반적으로 사용되는 네 가지 방법

1.hashmap.keySet(), 이 메서드는 키와 값을 가져올 수 있음, 2.Map.Entry
<x,x> 항목, 4.hashmap.values() 사용하기 쉽지 않고 가치 만 얻을 수 있습니다.

public static void main(String[] args) {
    
    
        HashMap<Integer, String> hashmap = new HashMap<>();
        hashmap.put(1,"gogo");
        hashmap.put(2,"wade");
        hashmap.put(3,"james");
        hashmap.put(4,"curry");
        // 1. 通过Map.keySet遍历key和value:
        for (int key : hashmap.keySet()){
    
    
            System.out.println("key: "+ key + "; value: " + hashmap.get(key));
        }
 
        //2. 通过Map.entrySet使用iterator遍历key和value:
        Iterator<Map.Entry<Integer, String>> it = hashmap.entrySet().iterator();
        while (it.hasNext()){
    
    
            Map.Entry<Integer, String> entry = it.next();
            System.out.println("key: "+ entry.getKey() + "; value: " + entry.getValue());
        }
 
        //3. 通过Map.entrySet遍历key和value
        for(Map.Entry<Integer, String> entry : hashmap.entrySet()){
    
    
            System.out.println("key: "+ entry.getKey() + "; value: " + entry.getValue());
        }
 
        //4. 通过Map.values()遍历所有的value,但不能遍历key
        for (String value : hashmap.values()) {
    
    
            System.out.println("value: "+value);
        }
    }

おすすめ

転載: blog.csdn.net/qq_32301683/article/details/108503213