Here you can find the source of putIfAbsent(Map
public static <K, V> V putIfAbsent(Map<K, V> map, K key, V value)
//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()); } }