Java Map Traversal Methods Guide

In Java, the Map interface has four different ways to iterate through a collection of key-value pairs, where each key is unique.

  1. Traversing with EntrySet: Traverse by iterating over the Entry objects in the Map. Entry objects represent each key-value pair in the Map.
Map<String, Integer> map = new HashMap<>();
// 添加键值对
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);

// 使用EntrySet遍历
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println(key + " = " + value);
}

This traversal method is suitable for situations where you need to simultaneously access both keys and values.

  1. Traversing with KeySet: Traversing through the keys collection in the Map to achieve traversal.
Map<String, Integer> map = new HashMap<>();
// 添加键值对
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);

// 使用KeySet遍历
for (String key : map.keySet()) {
    Integer value = map.get(key);
    System.out.println(key + " = " + value);
}

This traversal method is suitable for situations where only the keys need to be obtained.

  1. Iterating with Values: achieve iteration by traversing the values collection within the Map.
Map<String, Integer> map = new HashMap<>();
// 添加键值对
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);

// 使用Values遍历
for (Integer value : map.values()) {
    System.out.println(value);
}

This traversal method is suitable for cases where only the values need to be obtained.

  1. Traverse using Java 8’s forEach: Implement traversal by combining the forEach method of Map with Lambda expressions.
Map<String, Integer> map = new HashMap<>();
// 添加键值对
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);

// 使用forEach遍历
map.forEach((key, value) -> System.out.println(key + " = " + value));

This traversal method is newly added in Java 8, it is concise and flexible.

These are the four ways to traverse a map, and you can choose the appropriate method based on your specific needs.

bannerAds