EN
Java - get keys and values from HashMap
2
points
Short solution - get all keys and values
Map<String, Integer> map = new HashMap<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value : " + value);
}
Short solution - get only keys
Map<String, Integer> map = new HashMap<>();
Set<String> keys = map.keySet();
for (String key : keys) {
System.out.println("Key: " + key);
}
Short solution - get only values
Map<String, Integer> map = new HashMap<>();
Collection<Integer> values = map.values();
for (Integer value : values) {
System.out.println("Value: " + value);
}
Short solution - get all keys and values - Java 8
Map<String, Integer> map = new HashMap<>();
map.forEach((key, value) -> {
// use key and value variables
System.out.println("Key: " + key + ", Value : " + value);
});
1. Get all keys and values
import java.util.HashMap;
import java.util.Map;
public class Example1 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 10);
map.put("B", 20);
map.put("C", 30);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value : " + value);
}
}
}
Output:
Key: A, Value : 10
Key: B, Value : 20
Key: C, Value : 30
2. Get only keys
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Example2 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 10);
map.put("B", 20);
map.put("C", 30);
Set<String> keys = map.keySet();
for (String key : keys) {
System.out.println("Key: " + key);
}
}
}
Output:
Key: A
Key: B
Key: C
3. Get only values
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class Example3 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 10);
map.put("B", 20);
map.put("C", 30);
Collection<Integer> values = map.values();
for (Integer value : values) {
System.out.println("Value: " + value);
}
}
}
Output:
Value: 10
Value: 20
Value: 30
4. Get all keys and values - Java 8
import java.util.HashMap;
import java.util.Map;
public class Example4 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 10);
map.put("B", 20);
map.put("C", 30);
map.forEach((key, value) -> {
// use key and value variables
System.out.println("Key: " + key + ", Value : " + value);
});
}
}
Output:
Key: A, Value : 10
Key: B, Value : 20
Key: C, Value : 30