In Java, we can iterate through a HashMap in few different ways.
First of all, we need to import required packages:
1 2 3 4 5 |
import java.util.HashMap; import java.util.Map; |
Then, naturally, set our HashMap and put some data in there:
1 2 3 4 5 6 7 |
Map<Integer, String> pirates = new HashMap<Integer, String>(); pirates.put(1, "Jack Sparrow"); pirates.put(2, "Davy Jones"); pirates.put(3, "Blackbeard"); |
1. Values and Keys
The simplest way to iterate is using keys or values.
Using values:
1 2 3 4 5 |
for(String value : pirates.values()){ System.out.println(value + "\t"); } |
If we use keys the important thing is that we can find the values using only them by using get(key)
. Although it is a slow and not efficient method. In this example we print keys and values both in one line:
1 2 3 4 5 |
for(Integer key : pirates.keySet()){ System.out.println(key + "\t" + pirates.get(key)); } |
2. Using Entry
Another possibility is using entry
1 2 3 |
import java.util.Map.Entry; |
*.getKey()
and *.getValue()
.
1 2 3 4 5 6 |
for(Entry<Integer, String> entry : pirates.entrySet()){ System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue()); } |
3. Iterator
In Java, we can use Iterator object to iterate through elements. The same we can do here.
1 2 3 |
Iterator<Entry<Integer, String>> iterator = pirates.entrySet().iterator(); |
1 2 3 4 5 6 7 |
while(iterator.hasNext()){ Entry<Integer, String> entry = iterator.next(); System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue()); } |