Backend Development 10 min read

Four Methods to Traverse a Java Map Using keySet, entrySet and Iterators

This article demonstrates four practical ways to iterate over a Java HashMap—including enhanced for loops with keySet(), iterator-based loops with keySet(), enhanced for loops with entrySet(), and iterator-based loops with entrySet()—and provides a complete example that filters employee objects by salary, complete with full source code.

Top Architect
Top Architect
Top Architect
Four Methods to Traverse a Java Map Using keySet, entrySet and Iterators

Map is a core interface in Java; its inner interface Map.Entry represents a key‑value pair. Commonly used methods such as keySet() and entrySet() return a Set of keys or entries, enabling various traversal techniques.

1. Construct a HashMap and add elements

HashMap hashMap = new HashMap();
hashMap.put("三国演义", "罗贯中");
hashMap.put("水浒传", "施耐庵");
hashMap.put("西游记", "吴承恩");
hashMap.put("红楼梦", "曹雪芹");

2. Method One – keySet() with enhanced for loop

System.out.println("====1、先用keySet()取出所有key值,再取出对应value——增强for循环遍历====");
Set keyset = hashMap.keySet();
for (Object key : keyset) {
    System.out.println(key + "-" + hashMap.get(key));
}

3. Method Two – keySet() with Iterator

System.out.println("====2、先用keySet()取出所有key值,再取出对应value——使用迭代器遍历====");
Iterator iterator = keyset.iterator();
while (iterator.hasNext()) {
    Object key = iterator.next();
    System.out.println(key + "-" + hashMap.get(key));
}

4. Method Three – entrySet() with enhanced for loop

System.out.println("====3、通过entrySet()获得key-value值——增强for循环遍历====");
Set set = hashMap.entrySet();
for (Object obj : set) {
    Map.Entry entry = (Map.Entry) obj;
    System.out.println(entry.getKey() + "-" + entry.getValue());
}

5. Method Four – entrySet() with Iterator

System.out.println("====4、通过entrySet()获得key-value值——使用迭代器遍历====");
Set set1 = hashMap.entrySet();
Iterator iterator1 = set1.iterator();
while (iterator1.hasNext()) {
    Object obj = iterator1.next();
    Map.Entry entry = (Map.Entry) obj;
    System.out.println(entry.getKey() + "-" + entry.getValue());
}

6. Application Example – Filtering Employees by Salary

The following example creates a HashMap where the key is an employee ID and the value is an employee object. It then demonstrates two traversal methods (keySet with enhanced for loop and entrySet with iterator) to print employees whose salary exceeds 18,000.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapExercise {
    public static void main(String[] args) {
        HashMap
hashMap = new HashMap<>();
        hashMap.put(1, new employee("Tom", 20000.0, 1));
        hashMap.put(2, new employee("Jack", 10000.0, 2));
        hashMap.put(3, new employee("Bob", 30000.0, 3));
        hashMap.put(4, new employee("Marry", 17000.0, 4));

        // 1) keySet() + enhanced for loop
        System.out.println("====1、通过keySet()获取所有key值,再得到对应的value值——增强for循环遍历");
        Set
keyset = hashMap.keySet();
        for (Integer key : keyset) {
            employee e = (employee) hashMap.get(key);
            if (e.getSalary() > 18000) {
                System.out.println(e);
            }
        }

        // 2) entrySet() + iterator
        System.out.println("====2、通过entrySet()获取key-value值——使用迭代器遍历====");
        Set
> set = hashMap.entrySet();
        Iterator
> iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry
entry = iterator.next();
            employee e = entry.getValue();
            if (e.getSalary() > 18000) {
                System.out.println(e);
            }
        }
    }
}

class employee {
    private String name;
    private Double salary;
    private int id;
    public employee(String name, Double salary, int id) {
        this.name = name;
        this.salary = salary;
        this.id = id;
    }
    public String getName() { return name; }
    public Double getSalary() { return salary; }
    public int getId() { return id; }
    @Override
    public String toString() {
        return "employee{" + "name='" + name + '\'' + ", salary=" + salary + ", id=" + id + '}';
    }
}

Both traversal approaches produce the same filtered output, illustrating how to work with Map collections efficiently.

For Java 8 and later, these patterns can be further simplified with streams, but the underlying principles remain the same.

backendJavaHashMapCollectionsIteratorkeySetentrySetmap-iteration
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.