Saturday, August 31, 2019

Java – How to get Values by Keys from Map

Java Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

How to get Keys and Value from Map ?

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

Map map = new HashMap<>();

 // Get keys and values
 for (Map.Entry 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.
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 map = new HashMap<>();
        map.put("db", "oracle");
        map.put("username", "user1");
        map.put("password", "pass1");

        // Get keys and values
        for (Map.Entry entry : map.entrySet()) {
            String k = entry.getKey();
            String v = entry.getValue();
            System.out.println("Key: " + k + ", Value: " + v);
        }

        // Get all keys
        Set keys = map.keySet();
        for (String k : keys) {
            System.out.println("Key: " + k);
        }

        // Get all values
        Collection 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);
        });

    }
}


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


This is way to get Value by Key in Java Map, hope this article can help you guys.
Thank You.

0 komentar:

Post a Comment