首页 小组 问答 话题 好文 素材 用户 唠叨 我的社区

[分享]Hashmap的方法如何实现迭代

道亮_(:з」∠)_Lv.1管理员
2024-07-10 11:36:26
0
102

在Java中,可以使用HashMap的entrySet()方法来获取包含键值对的Set集合,然后通过迭代器或者增强型for循环来遍历这个Set集合,从而实现对HashMap的迭代操作。具体实现如下:

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

public class Main {
    public static void main(String[] args) {
        // 创建一个HashMap
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("A", 1);
        hashMap.put("B", 2);
        hashMap.put("C", 3);
        
        // 使用entrySet()方法获取键值对集合
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println("Key: " + key + ", Value: " + value);
        }
    }
}


通过上面的代码,我们可以实现对HashMap的迭代操作,并输出键值对的内容。

道亮_(:з」∠)_
道亮_(:з」∠)_

104 天前

签名 : 不交僧道,便是好人。   102       0
评论
站长交流