Main Tutorials

Java – How to get keys and values from Map

In Java, we can get the keys and values via map.entrySet()


	Map<String, String> map = new HashMap<>();

	// 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);
	}

	// Java 8
	map.forEach((k, v) -> {
		System.out.println("Key: " + k + ", Value: " + v);
	});

Full example.

JavaMapExample.java

package com.mkyong;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class JavaMapExample {

    public static void main(String[] args) {

        Map<String, String> map = new HashMap<>();
        map.put("db", "oracle");
        map.put("username", "user1");
        map.put("password", "pass1");

        // 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);
        }

        // Java 8
        map.forEach((k, v) -> {
            System.out.println("Key: " + k + ", Value: " + v);
        });

    }
}

Output


Key: password, Value: pass1
Key: db, Value: oracle
Key: username, Value: user1

Key: password
Key: db
Key: username

Value: pass1
Value: oracle
Value: user1

Key: password, Value: pass1
Key: db, Value: oracle
Key: username, Value: user1

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Atul
4 years ago

Thanks

Mgh
2 years ago

NICE