How to get keys and values from Map in Java?
In this section, we will show you how to get keys and values from Map in Java.
Java 8 Example
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("host", "knowledgefactory.net");
map.put("username", "knowledgefactory");
map.put("password", "mypassword");
// Java 8
map.forEach((k, v) -> {
System.out.println("Key: " + k + ", Value: " + v);
});
}
}
Console Output:
Key: password, Value: mypassword
Key: host, Value: knowledgefactory.net
Key: username, Value: knowledgefactory
Old style
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("host", "knowledgefactory.net");
map.put("username", "knowledgefactory");
map.put("password", "mypassword");
// Get keys and values
for (Map.Entry<String, String> entry : map.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
System.out.println("Key: " + k + ", Value: " + v);
}
// Get all keys
Set<String> keys = map.keySet();
for (String k : keys) {
System.out.println("Key: " + k);
}
// Get all values
Collection<String> values = map.values();
for (String v : values) {
System.out.println("Value: " + v);
}
}
}
Console Output:
Key: password, Value: mypassword Key: host, Value: knowledgefactory.net Key: username, Value: knowledgefactory Key: password Key: host Key: username Value: mypassword Value: knowledgefactory.net Value: knowledgefactory
More...