- Advanced for loop or for each
- Iterator + while loop
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class IterateHashMap{ public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("A",1); map.put("B",2); map.put("C",3); map.put("D",4); //for each loop System.out.println("for each:"); for (Map.Entry mapentry : map.entrySet()) { System.out.println("key: "+mapentry.getKey() + " | value: " + mapentry.getValue()); } //iterator and while loop System.out.println("Iterator + while loop"); Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry mapentry = (Map.Entry) iterator.next(); System.out.println("key: "+mapentry.getKey() + " | value: " + mapentry.getValue()); } } }Execution:
Boucle for: Key: D | value: 1 Key: A | value: 2 Key: B | value: 3 Key: C | value: 4 Boucle whileIn both cases, we get a set map of key-value data in the object Map.Entry. In for loop, we used entrySet () method of the Map class. In the while loop, was recovered an Iterator object and after obtaining all key-value, then we cast Map.Entry to print the keys and values with both getKey () and getValue () method.Key: D | value: 1 Key: A | value: 2 Key: B | value: 3 Key: C | value: 4
References:
Iterate through a HashMap
No comments:
Post a Comment