Gets either the value in the map for a key or the default value if there is no value. - Java java.util

Java examples for java.util:Map Key

Description

Gets either the value in the map for a key or the default value if there is no value.

Demo Code


//package com.java2s;

import java.util.*;

public class Main {
    /**//ww w . j av  a  2 s. c  o m
     * Gets either the value in the map for a key or the default value if there is no value.
     *
     * @param map          The map to get the value from.
     * @param key          The key to get
     * @param defaultValue The default value if there is no value for the key in the map
     * @return Either the value in the map for key, or the default value passed in.
     * @throws NullPointerException If either map or key are null.
     */
    public static <K, V> V getValue(final Map<K, ? extends V> map,
            final K key, final V defaultValue) {
        if (key == null) {
            throw new NullPointerException("Key cannot be null");
        }
        if (map.containsKey(key)) {
            return map.get(key);
        } else {
            return defaultValue;
        }
    }
}

Related Tutorials