EN
Java - iterate over keys in HashMap
8 points
Short solution - using forEach()
from Java 8:
xxxxxxxxxx
1
Map<String, Integer> map = new HashMap<>();
2
3
map.keySet().forEach(key -> {
4
// use key variable
5
System.out.println("Key: " + key);
6
});
Short solution - using for loop and Map
keySet()
:
xxxxxxxxxx
1
Map<String, Integer> map = new HashMap<>();
2
3
for (String key : map.keySet()) {
4
System.out.println("Key: " + key);
5
}
Short solution - iterate over entire map and use only keys with forEach()
from Java 8:
xxxxxxxxxx
1
Map<String, Integer> map = new HashMap<>();
2
3
map.forEach((key, value) -> {
4
// we use only key variable
5
System.out.println("Key: " + key);
6
});
Short solution - iterate over entire map with entrySet()
and use only keys:
xxxxxxxxxx
1
Map<String, Integer> map = new HashMap<>();
2
3
for (Map.Entry<String, Integer> entry : map.entrySet()) {
4
String key = entry.getKey();
5
// Integer value = entry.getValue();
6
7
System.out.println("Key: " + key);
8
}
xxxxxxxxxx
1
import java.util.HashMap;
2
import java.util.Map;
3
4
public class Example1 {
5
6
public static void main(String[] args) {
7
8
Map<String, Integer> map = new HashMap<>();
9
map.put("A", 10);
10
map.put("B", 20);
11
map.put("C", 30);
12
13
map.keySet().forEach(key -> {
14
// use key variable
15
System.out.println("Key: " + key);
16
});
17
}
18
}
Output:
xxxxxxxxxx
1
Key: A
2
Key: B
3
Key: C
xxxxxxxxxx
1
import java.util.HashMap;
2
import java.util.Map;
3
4
public class Example2 {
5
6
public static void main(String[] args) {
7
8
Map<String, Integer> map = new HashMap<>();
9
map.put("A", 10);
10
map.put("B", 20);
11
map.put("C", 30);
12
13
for (String key : map.keySet()) {
14
System.out.println("Key: " + key);
15
}
16
}
17
}
Output:
xxxxxxxxxx
1
Key: A
2
Key: B
3
Key: C
We can also iterate over entire map and use only keys with forEach() from Java 8
xxxxxxxxxx
1
import java.util.HashMap;
2
import java.util.Map;
3
4
public class Example3 {
5
6
public static void main(String[] args) {
7
8
Map<String, Integer> map = new HashMap<>();
9
map.put("A", 10);
10
map.put("B", 20);
11
map.put("C", 30);
12
13
map.forEach((key, value) -> {
14
// we use only key variable
15
System.out.println("Key: " + key);
16
});
17
}
18
}
Output:
xxxxxxxxxx
1
Key : A
2
Key : B
3
Key : C
We can also iterate over entire map with entrySet() and use only keys
xxxxxxxxxx
1
import java.util.HashMap;
2
import java.util.Map;
3
4
public class Example4 {
5
6
public static void main(String[] args) {
7
8
Map<String, Integer> map = new HashMap<>();
9
map.put("A", 10);
10
map.put("B", 20);
11
map.put("C", 30);
12
13
for (Map.Entry<String, Integer> entry : map.entrySet()) {
14
String key = entry.getKey();
15
// Integer value = entry.getValue();
16
17
System.out.println("Key: " + key);
18
}
19
}
20
}
Output:
xxxxxxxxxx
1
Key : A
2
Key : B
3
Key : C