From dc4a937262a4440b3154c51693a10152cf047547 Mon Sep 17 00:00:00 2001 From: Sergey Kapralov Date: Tue, 23 Aug 2016 10:39:37 +0300 Subject: [PATCH] Added missing map methods --- .../org/teavm/classlib/java/util/TMap.java | 75 ++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/classlib/src/main/java/org/teavm/classlib/java/util/TMap.java b/classlib/src/main/java/org/teavm/classlib/java/util/TMap.java index 799db2ca0..2d078a6fd 100644 --- a/classlib/src/main/java/org/teavm/classlib/java/util/TMap.java +++ b/classlib/src/main/java/org/teavm/classlib/java/util/TMap.java @@ -15,6 +15,9 @@ */ package org.teavm.classlib.java.util; +import java.util.function.BiFunction; +import java.util.function.Function; + /** * * @author Alexey Andreev @@ -43,7 +46,7 @@ public interface TMap { V put(K key, V value); V remove(Object key); - + void putAll(TMap m); void clear(); @@ -53,4 +56,74 @@ public interface TMap { TCollection values(); TSet> entrySet(); + + default boolean replace(K key, V value, V newValue) { + if (containsKey(key) && TObjects.equals(get(key), value)) { + put(key, newValue); + return true; + } else { + return false; + } + } + + default V replace(K key, V value) { + if (containsKey(key)) { + return put(key, value); + } else { + return null; + } + } + + default V computeIfAbsent(K key, Function mappingFunction) { + V v = get(key); + if (v == null) { + V newValue = mappingFunction.apply(key); + if (newValue != null) { + put(key, newValue); + } + return newValue; + } + return v; + } + + default V computeIfPresent(K key, BiFunction remappingFunction) { + V v = get(key); + if (v != null) { + V oldValue = v; + V newValue = remappingFunction.apply(key, oldValue); + if (newValue != null) { + return put(key, newValue); + } else { + return remove(key); + } + } + return v; + } + + default V compute(K key, BiFunction remappingFunction) { + V oldValue = get(key); + V newValue = remappingFunction.apply(key, oldValue); + if (oldValue != null) { + if (newValue != null) { + return put(key, newValue); + } else { + return remove(key); + } + } else if (newValue != null) { + return put(key, newValue); + } else { + return null; + } + } + + default V merge(K key, V value, BiFunction remappingFunction) { + V oldValue = get(key); + V newValue = (oldValue == null) ? value + : remappingFunction.apply(oldValue, value); + if (newValue == null) { + return remove(key); + } else { + return put(key, newValue); + } + } }