📜  java iterate hashmap - Java (1)

📅  最后修改于: 2023-12-03 14:42:14.686000             🧑  作者: Mango

Java Iterate Hashmap

Iterating over a hashmap in Java is a common task for a programmer. In this tutorial, we will learn how to iterate over a hashmap in Java.

How HashMap Works

A hashmap is a data structure that stores key-value pairs. Each element is stored as a Node object, which contains the key, the value, and a reference to the next node.

To retrieve a value from a hashmap, the key is input into a hash function, which returns the index of the element in the array. If that index already contains an element, a reference to that element is maintained in the next pointer of the current element, creating a linked list.

Iterating Over a HashMap

To iterate over a hashmap in Java, we can use the EntrySet object and a for loop. Here's an example:

HashMap<String, String> myHashMap = new HashMap<String, String>();
myHashMap.put("key1", "value1");
myHashMap.put("key2", "value2");
myHashMap.put("key3", "value3");
for (Map.Entry<String, String> entry : myHashMap.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key + " : " + value);
}

In this example, we create a new HashMap object called myHashMap and insert three key-value pairs into it. Then, we use a for loop to iterate over the EntrySet of myHashMap. For each entry, we extract the key and value using the getKey and getValue methods of the Map.Entry class, respectively. Finally, we print out the key and value using the System.out.println method.

The output of this code would be:

key1 : value1
key2 : value2
key3 : value3
Conclusion

In this tutorial, we learned how a hashmap works and how to iterate over one in Java. We hope you found this tutorial helpful!