Java Map Put putIfAbsentGet(Map map, K key, V value)

Here you can find the source of putIfAbsentGet(Map map, K key, V value)

Description

Puts the value into the map if the key is not present.

License

Open Source License

Parameter

Parameter Description
K the map key type
V the map value type
map the map to populate, not null
key the key
value the value

Return

the contents of the map for the key

Declaration

public static <K, V> V putIfAbsentGet(Map<K, V> map, K key, V value) 

Method Source Code

//package com.java2s;
/**//from   ww  w  .  j a va  2  s . c o m
 * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */

import java.util.Map;

public class Main {
    /**
     * Puts the value into the map if the key is not present.
     * <p>
     * This is most useful in building up a map of maps, or similar structure.
     * 
     * @param <K> the map key type
     * @param <V> the map value type
     * @param map  the map  to populate, not null
     * @param key  the key
     * @param value  the value
     * @return the contents of the map for the key
     */
    public static <K, V> V putIfAbsentGet(Map<K, V> map, K key, V value) {
        V existing = map.get(key);
        if (existing != null) {
            return existing;
        }
        map.put(key, value);
        return value;
    }
}

Related

  1. putIfAbsent(Map map, K key, V value)
  2. putIfAbsent(Map map, K key, V value)
  3. putIfAbsent(Map map, K key, V value)
  4. putIfAbsent(Map map, S key, T val)
  5. putIfAbsent(Map map, String name, String value)
  6. putIfNonNull(Map map, K key, V value)
  7. putIfNotExist(Map map, K key, V value)
  8. putIfNotExists(final K key, final V value, final Map map)
  9. putIfNotExists(Map map, K key, V value)