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...

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete