租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

hashmap怎么遍历,hashmap遍历keyset

发布时间:2024-01-04 05:21:23

hashmap怎样遍历

在Java中,可使用以下方法遍历HashMap:

  1. 使用键集遍历:使用keySet()方法获得HashMap中的键的集合,然后使用for-each循环遍历键集,通过键获得对应的值。
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加键值对
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);

// 遍历
for (String key : hashMap.keySet()) {
    Integer value = hashMap.get(key);
    System.out.println(key + ": " + value);
}
  1. 使用值集遍历:使用values()方法获得HashMap中的值的集合,然后使用for-each循环遍历值集。
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加键值对
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);

// 遍历
for (Integer value : hashMap.values()) {
    System.out.println(value);
}
  1. 使用Entry集合遍历:使用entrySet()方法获得HashMap中的键值对的集合,然后使用for-each循环遍历Entry集合,通过Entry获得键和值。
HashMap<String, Integer> hashMap = new 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();
    System.out.println(key + ": " + value);
}

这些方法可以根据具体需求选择使用,根据键遍历可以获得键和值,根据值遍历可以只获得值,而使用Entry集合遍历可以同时获得键和值。