EN
Java - iterate over values in HashMap
1 points
Short solution - using forEach() from Java 8:
xxxxxxxxxx
1
Map<String, Integer> map = new HashMap<>();
2
3
map.values().forEach(value -> {
4
// use value variable
5
System.out.println("Value: " + value);
6
});
Short solution - using for loop and Map values():
xxxxxxxxxx
1
Map<String, Integer> map = new HashMap<>();
2
3
for (Integer value : map.values()) {
4
System.out.println("Value: " + value);
5
}
Short solution - iterate over entire map and use only values with forEach() from Java 8:
xxxxxxxxxx
1
Map<String, Integer> map = new HashMap<>();
2
3
map.forEach((key, value) -> {
4
// we use only value variable
5
System.out.println("Value : " + value);
6
});
Short solution - iterate over entire map with entrySet() and use only values:
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("Value : " + value);
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.values().forEach(value -> {
14
// use value variable
15
System.out.println("Value: " + value);
16
});
17
}
18
}
Output:
xxxxxxxxxx
1
Value: 10
2
Value: 20
3
Value: 30
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 (Integer value : map.values()) {
14
System.out.println("Value: " + value);
15
}
16
}
17
}
Output:
xxxxxxxxxx
1
Value: 10
2
Value: 20
3
Value: 30
We can also iterate over entire map and use only values 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 value variable
15
System.out.println("Value : " + value);
16
});
17
}
18
}
Output:
xxxxxxxxxx
1
Value : 10
2
Value : 20
3
Value : 30
We can also iterate over entire map with entrySet() and use only values.
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("Value : " + value);
18
}
19
}
20
}
Output:
xxxxxxxxxx
1
Value : 10
2
Value : 20
3
Value : 30