Hashmap的方法如何實(shí)現(xiàn)迭代

小樊
90
2024-07-10 05:04:20
欄目: 編程語言

在Java中,可以使用HashMap的entrySet()方法來獲取包含鍵值對(duì)的Set集合,然后通過迭代器或者增強(qiáng)型for循環(huán)來遍歷這個(gè)Set集合,從而實(shí)現(xiàn)對(duì)HashMap的迭代操作。具體實(shí)現(xiàn)如下:

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // 創(chuàng)建一個(gè)HashMap
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("A", 1);
        hashMap.put("B", 2);
        hashMap.put("C", 3);
        
        // 使用entrySet()方法獲取鍵值對(duì)集合
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println("Key: " + key + ", Value: " + value);
        }
    }
}

通過上面的代碼,我們可以實(shí)現(xiàn)對(duì)HashMap的迭代操作,并輸出鍵值對(duì)的內(nèi)容。

0