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
1import java.util.HashMap;
2import java.util.Iterator;
3import java.util.Map;
4import java.util.stream.Stream;
5
6class MapUtil
7{
8 // Program to print all keys present in the Map using keySet() in Java
9 public static void main (String[] args)
10 {
11 Map<Integer, String> map = new HashMap<>();
12 map.put(1, "One");
13 map.put(2, "Two");
14
15 // 1. using Iterator
16 Iterator<Integer> itr = map.keySet().iterator();
17 while (itr.hasNext()) {
18 System.out.println(itr.next());
19 }
20
21 // 2. For-each Loop
22 for (Integer key : map.keySet()) {
23 System.out.println(key);
24 }
25
26 // 3. Java 8 - Collection.iterator() + Iterator.forEachRemaining()
27 map.keySet().iterator()
28 .forEachRemaining(System.out::println);
29
30 // 4. Java 8 - Collection.stream() + Stream.forEach()
31 map.keySet().stream()
32 .forEach(System.out::println);
33
34 // Java 8 - Stream.of() + Collection.toArray() + Stream.forEach()
35 Stream.of(map.keySet().toArray())
36 .forEach(System.out::println);
37
38 // 5. Convert to String
39 System.out.println(map.keySet().toString());
40
41 // Java 8
42 Stream.of(map.keySet().toString())
43 .forEach(System.out::println);
44 }
45}
46
1// Java 8 - Collection.iterator() + Iterator.forEachRemaining()
2 map.keySet().iterator()
3 .forEachRemaining(System.out::println);