Iterating over any of the Map implementation(Hashmap, TreeMap etc) is not very straight forward compared to other collections as it is two steps process. There are different ways you can iterate over Map, but in this example we will see how to iterate using advanced for loop and using the Iterator object. We will use following three different ways to traverse.
Follow us on social media to get latest tutorials, tips and tricks on java.
Please share us on social media if you like the tutorial.
- Using Iterator interface
- Using entrySet() and for loop
- Using keyset() and for loop
Java Program to Iterate HashMap
package com.tutorialsdesk.collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapIterator {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("ONE", 1);
map.put("TWO", 2);
map.put("THREE", 3);
map.put("FOUR", 4);
map.put("FIVE", 5);
System.out.println("Using Iterator");
Set<String> setOfKeys = map.keySet();
Iterator<String> iterator = setOfKeys.iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
Integer value = map.get(key);
System.out.println(key+" :: "+ value);
//iterator.remove();
//You can remove elements while iterating.
}
System.out.println("Using EntrySet");
for(Map.Entry<String, Integer> maps : map.entrySet()){
System.out.println(maps.getKey() +" :: "+ maps.getValue());
//if you uncomment below code, it will throw
java.util.ConcurrentModificationException
//map.remove("FIVE");
}
System.out.println("Using KeySet");
for(String key: map.keySet()){
System.out.println(key +" :: "+ map.get(key));
//if you uncomment below code, it will throw
java.util.ConcurrentModificationException
//map.remove("FIVE");
}
}
}
Output
Below is the output of above programUsing IteratorNEXT READ Read and Parse a CSV file in java.
ONE :: 1
TWO :: 2
THREE :: 3
FOUR :: 4
FIVE :: 5
Using EntrySet
ONE :: 1
TWO :: 2
THREE :: 3
FOUR :: 4
FIVE :: 5
Using KeySet
ONE :: 1
TWO :: 2
THREE :: 3
FOUR :: 4
FIVE :: 5
Follow us on social media to get latest tutorials, tips and tricks on java.
Please share us on social media if you like the tutorial.
Source:http://www.tutorialsdesk.com/2014/10/how-to-iterate-through-map-or-hashmap.html
Tidak ada komentar:
Posting Komentar