Puzzler: Nested computeIfAbsent
Join the DZone community and get the full member experience.
Join For FreeThe Java 8 libraries have a new method on map, computeIfAbsent. This is very useful way to turn your Map into a cache of objects associated with a key.
However, there is a combination you might not have considered; what happens if you call computeIfAbsent inside itself.
map.computeIfAbsent(Key.Hello, s -> { map.computeIfAbsent(Key.Hello, t -> 1); return 2; }); enum Key {Hello}
HashMap: {Hello=2} WeakHashMap: {Hello=2} TreeMap: {Hello=2} IdentityHashMap: {Hello=2} EnumMap: {Hello=2} Hashtable: {Hello=2, Hello=1} LinkedHashMap: {Hello=1, Hello=2} ConcurrentSkipListMap: {Hello=1} ConcurrentHashMap:
public class A { public static void main(String[] args) { for (Map map : new Map[]{ new HashMap<>(), new WeakHashMap<>(), new TreeMap<>(), new IdentityHashMap<>(), new EnumMap<>(Key.class), new Hashtable<>(), new LinkedHashMap<>(), new ConcurrentSkipListMap<>(), new ConcurrentHashMap<>() }) { System.out.print(map.getClass().getSimpleName() + ": "); map.computeIfAbsent(Key.Hello, s -> { map.computeIfAbsent(Key.Hello, t -> 1); return 2; }); System.out.println(map); } } enum Key {Hello} }
The method compute() has similar results
HashMap: {Hello=null2} WeakHashMap: {Hello=null2} TreeMap: {Hello=null2} IdentityHashMap: {Hello=null2} EnumMap: {Hello=null2} Hashtable: {Hello=null2, Hello=1} LinkedHashMap: {Hello=1, Hello=null2} ConcurrentSkipListMap: {Hello=12} ConcurrentHashMap:
Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments