5 Best Ways to Iterate Over HashMap in Java

In this article, we will discuss five different ways to iterate over a HashMap in Java. Each method has its own advantages and use cases. We will cover the following methods:

  1. Iterate through a HashMap EntrySet using an Iterator
  2. Iterate through a HashMap KeySet using an Iterator
  3. Iterate through a HashMap using a For-each Loop
  4. Iterate through a HashMap using Lambda Expressions
  5. Loop through a HashMap using the Stream API

1. Iterate through a HashMap EntrySet using an Iterator

The entrySet method returns a set view of the mappings contained in the HashMap. Using an Iterator to traverse the entrySet allows you to access both the keys and values.

Example

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

public class IterateEntrySetUsingIterator {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Cherry", 3);

        Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Integer> entry = iterator.next();
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}

Output:

Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Cherry, Value: 3

2. Iterate through a HashMap KeySet using an Iterator

The keySet method returns a set view of the keys contained in the HashMap. Using an Iterator to traverse the keySet allows you to access each key and then get the corresponding value.

Example

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

public class IterateKeySetUsingIterator {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Cherry", 3);

        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            System.out.println("Key: " + key + ", Value: " + map.get(key));
        }
    }
}

Output:

Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Cherry, Value: 3

3. Iterate through a HashMap using a For-each Loop

The enhanced for loop (for-each loop) provides a concise way to iterate over the entries of a HashMap.

Example

import java.util.HashMap;
import java.util.Map;

public class IterateUsingForEachLoop {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Cherry", 3);

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}

Output:

Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Cherry, Value: 3

4. Iterating through a HashMap using Lambda Expressions

Java 8 introduced lambda expressions, which provide a more concise way to iterate over the entries of a HashMap.

Example

import java.util.HashMap;
import java.util.Map;

public class IterateUsingLambda {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Cherry", 3);

        map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
    }
}

Output:

Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Cherry, Value: 3

5. Loop through a HashMap using the Stream API

Java 8 also introduced the Stream API, which can be used to process collections of objects in a functional style.

Example

import java.util.HashMap;
import java.util.Map;

public class IterateUsingStreamAPI {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Cherry", 3);

        map.entrySet().stream()
            .forEach(entry -> System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()));
    }
}

Output:

Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Cherry, Value: 3

Conclusion

These five methods provide different ways to iterate over a HashMap in Java, each with its own advantages:

  1. EntrySet with Iterator: Allows access to both keys and values with an iterator.
  2. KeySet with Iterator: Iterates over keys and retrieves values.
  3. For-each Loop: Simple and concise iteration over map entries.
  4. Lambda Expressions: Concise and functional style introduced in Java 8.
  5. Stream API: Functional programming approach for more complex operations.

Choose the method that best fits your needs based on the context and requirements of your application.

Comments

  1. Hello, I want to translate this article into Chinese. Can I get translation authorization?

    ReplyDelete

Post a Comment

Leave Comment