1// 1. for-each with Entry
2Map<Integer, Integer> map = new HashMap<Integer, Integer>();
3for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
4 System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
5}
6
7
8// 2. for-each with key or value each (faster)
9Map<Integer, Integer> map = new HashMap<Integer, Integer>();
10//iterating over keys only
11for (Integer key : map.keySet()) {
12 System.out.println("Key = " + key);
13}
14
15//iterating over values only
16for (Integer value : map.values()) {
17 System.out.println("Value = " + value);
18}
19
20
21// 3. Using Iterator
22Map<Integer, Integer> map = new HashMap<Integer, Integer>();
23// With Generic
24Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
25while (entries.hasNext()) {
26 Map.Entry<Integer, Integer> entry = entries.next();
27 System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
28}
29
30// No Generic
31Map map = new HashMap();
32Iterator entries = map.entrySet().iterator();
33while (entries.hasNext()) {
34 Map.Entry entry = (Map.Entry) entries.next();
35 Integer key = (Integer)entry.getKey();
36 Integer value = (Integer)entry.getValue();
37 System.out.println("Key = " + key + ", Value = " + value);
38}
39
1Map<String, Integer> items = new HashMap<>();
2items.put("A", 10);
3items.put("B", 20);
4items.put("C", 30);
5items.put("D", 40);
6items.put("E", 50);
7items.put("F", 60);
8
9items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
10
11items.forEach((k,v)->{
12 System.out.println("Item : " + k + " Count : " + v);
13 if("E".equals(k)){
14 System.out.println("Hello E");
15 }
16});
1Map<String, String> map = ...
2for (Map.Entry<String, String> entry : map.entrySet()) {
3 System.out.println(entry.getKey() + "/" + entry.getValue());
4}
1public void iterateUsingEntrySet(Map<String, Integer> map) {
2 for (Map.Entry<String, Integer> entry : map.entrySet()) {
3 System.out.println(entry.getKey() + ":" + entry.getValue());
4 }
5}
6
1public void iterateUsingLambda(Map<String, Integer> map) {
2 map.forEach((k, v) -> System.out.println((k + ":" + v)));
3}
4