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);