Linux 拨号vps windows公众号手机端

hashmap怎么遍历

lewis 8年前 (2017-04-09) 阅读数 15 #程序编程
文章标签 hashmap

遍历HashMap可以使用以下几种方法:

  1. 使用Iterator遍历:
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到HashMap
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);

Iterator<Map.Entry<String, Integer>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();
    String key = entry.getKey();
    Integer value = entry.getValue();
    // 在这里处理key和value
}
  1. 使用For-Each循环遍历:
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到HashMap
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);

for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    // 在这里处理key和value
}
  1. 遍历所有的Key:
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到HashMap
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);

for (String key : hashMap.keySet()) {
    Integer value = hashMap.get(key);
    // 在这里处理key和value
}
  1. 遍历所有的Value:
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到HashMap
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);

for (Integer value : hashMap.values()) {
    // 在这里处理value
}

请根据具体的需求选择合适的遍历方法。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门