Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to use Iterator to loop through the Map key set?
First, create a HashMap, which is to be iterated −
Map<String, String>map = new LinkedHashMap<>();
map.put("Jack","0");
map.put("Tim", "1");
map.put("David","2");
map.put("Tom", "3");
map.put("Kevin", "4");
Now, use Iterator to map through keyset −
Iterator iterator = map.keySet().iterator();
Iterate through all the pairs −
while (iterator.hasNext()) {
String resKey = (String) iterator.next();
System.out.println("Rank of " + resKey + " is " + map.get(resKey));
}
Example
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class Demo {
public static void main(String[] args) {
Map<String, String>map = new LinkedHashMap<>();
map.put("Jack","0");
map.put("Tim", "1");
map.put("David","2");
map.put("Tom", "3");
map.put("Kevin", "4");
map.put("Jeff", "5");
map.put("Katie","6");
map.put("Steve", "7");
map.put("Andrew", "8");
map.put("Angelina", "9");
String str = (String) map.get("David");
System.out.println("Rank of David = " + str);
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String resKey = (String) iterator.next();
System.out.println("Rank of " + resKey + " is " + map.get(resKey));
}
}
}
Output
Rank of David = 2 Rank of Jack is 0 Rank of Tim is 1 Rank of David is 2 Rank of Tom is 3 Rank of Kevin is 4 Rank of Jeff is 5 Rank of Katies is 6 Rank of Steve is 7 Rank of Andrew is 8 Rank of Angelina is 9
Advertisements
