Get a value from a Map or a default value in Java

In this source code example, we will you how to get a value from a Map or a default value in Java.

Get a value from a Map or a default value in Java


import java.util.HashMap;
import java.util.Map;

public class Main {

    public static void main(String[] args) {

        Map map = new HashMap<>();

        map.put("postgresql", "127.0.0.1:5432");
        map.put("mysql", "127.0.0.1:3306");
        map.put("cassandra", "127.0.0.1:9042");

        String hp1 = map.getOrDefault("derby", "127.0.0.1:27017");
        String hp2 = map.getOrDefault("mysql", "127.0.0.1:27017");

        System.out.println("hp1: " + hp1);
        System.out.println("hp2: " + hp2);
    }

}

Output:

hp1: 127.0.0.1:27017
hp2: 127.0.0.1:3306

Related HashMap Source Code Examples


Comments