hashmap怎么遍历

   2025-02-05 8250
核心提示:遍历HashMap可以使用以下几种方法:使用Iterator遍历:HashMapString, Integer hashMap = new HashMap();// 添加元素到HashMapha

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

使用Iterator遍历:
HashMap<String, Integer> hashMap = new HashMap<>();// 添加元素到HashMaphashMap.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}
使用For-Each循环遍历:
HashMap<String, Integer> hashMap = new HashMap<>();// 添加元素到HashMaphashMap.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}
遍历所有的Key:
HashMap<String, Integer> hashMap = new HashMap<>();// 添加元素到HashMaphashMap.put("A", 1);hashMap.put("B", 2);hashMap.put("C", 3);for (String key : hashMap.keySet()) {    Integer value = hashMap.get(key);    // 在这里处理key和value}
遍历所有的Value:
HashMap<String, Integer> hashMap = new HashMap<>();// 添加元素到HashMaphashMap.put("A", 1);hashMap.put("B", 2);hashMap.put("C", 3);for (Integer value : hashMap.values()) {    // 在这里处理value}

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言