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

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

Description

Adds the specified item to a map if it does not already exist.

License

Apache License

Declaration

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

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.util.Map;

public class Main {
    /**/*  w w  w.j  a  v  a  2 s  .c om*/
     *  Adds the specified item to a map if it does not already exist. Returns
     *  either the added item or the existing mapping.
     *  <p>
     *  <em>Note:</em>    The return behavior differs from <code>Map.put()</code>,
     *                    in that it returns the new value if there was no prior
     *                    mapping. I find this more useful, as I typically want
     *                    to do something with the mapping.
     *  <p>
     *  <em>Warning:</em> This operation is not synchronized. In most cases, a
     *                    better approach is to use {@link DefaultMap}, with a
     *                    functor to generate new entries.
     *
     *  @since 1.0.12
     */
    public static <K, V> V putIfAbsent(Map<K, V> map, K key, V value) {
        if (!map.containsKey(key)) {
            map.put(key, value);
            return value;
        }

        return map.get(key);
    }

    /**
     *  Adds entries from <code>add</code> to <code>base</code> where there is not
     *  already a mapping with the same key.
     *
     *  @since 1.0.14
     */
    public static <K, V> void putIfAbsent(Map<K, V> base, Map<K, V> add) {
        for (Map.Entry<K, V> entry : add.entrySet())
            putIfAbsent(base, entry.getKey(), entry.getValue());
    }
}

Related

  1. putDeepValue(Map map, String keyPath, T v)
  2. putIfAbsent(final Map from, final Map to)
  3. putIfAbsent(Map from, Map to)
  4. putIfAbsent(Map map, K key, V value)
  5. putIfAbsent(Map map, K key, V value)
  6. putIfAbsent(Map map, S key, T val)
  7. putIfAbsent(Map map, String name, String value)
  8. putIfAbsentGet(Map map, K key, V value)
  9. putIfNonNull(Map map, K key, V value)