com.landawn.abacus.util.Maps Maven / Gradle / Ivy
Show all versions of abacus-android-se-jdk7 Show documentation
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.landawn.abacus.util;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import com.landawn.abacus.DirtyMarker;
import com.landawn.abacus.exception.AbacusException;
import com.landawn.abacus.util.Fn.Suppliers;
import com.landawn.abacus.util.function.IntFunction;
import com.landawn.abacus.util.function.Supplier;
/**
* Note: It's copied from OpenJDK at: http://hg.openjdk.java.net/jdk8u/hs-dev/jdk
*
*
* Import the useful default Map methods from JDK 1.8 for programming on JDK 7 and Android.
*
*/
public final class Maps {
private Maps() {
// Utility class.
}
public static Map newMap(Collection extends T> c, final Try.Function super T, ? extends K, E> keyExtractor) throws E {
N.checkArgNotNull(keyExtractor);
if (N.isNullOrEmpty(c)) {
return new HashMap();
}
final Map result = new HashMap<>(N.initHashCapacity(c.size()));
for (T e : c) {
result.put(keyExtractor.apply(e), e);
}
return result;
}
public static Map newLinkedHashMap(Collection extends T> c, final Try.Function super T, ? extends K, E> keyExtractor)
throws E {
N.checkArgNotNull(keyExtractor);
if (N.isNullOrEmpty(c)) {
return new LinkedHashMap();
}
final Map result = new LinkedHashMap<>(N.initHashCapacity(c.size()));
for (T e : c) {
result.put(keyExtractor.apply(e), e);
}
return result;
}
public static Map newMap(Collection extends T> c,
final Try.Function super T, ? extends K, E> keyExtractor, final Try.Function super T, ? extends V, E2> valueExtractor) throws E, E2 {
N.checkArgNotNull(keyExtractor);
N.checkArgNotNull(valueExtractor);
if (N.isNullOrEmpty(c)) {
return new HashMap();
}
final Map result = new HashMap<>(N.initHashCapacity(c.size()));
for (T e : c) {
result.put(keyExtractor.apply(e), valueExtractor.apply(e));
}
return result;
}
public static , E extends Exception, E2 extends Exception> M newMap(Collection extends T> c,
final Try.Function super T, ? extends K, E> keyExtractor, final Try.Function super T, ? extends V, E2> valueExtractor,
final IntFunction mapSupplier) throws E, E2 {
N.checkArgNotNull(keyExtractor);
N.checkArgNotNull(valueExtractor);
if (N.isNullOrEmpty(c)) {
return mapSupplier.apply(0);
}
final M result = mapSupplier.apply(c.size());
for (T e : c) {
result.put(keyExtractor.apply(e), valueExtractor.apply(e));
}
return result;
}
@SuppressWarnings("rawtypes")
static Map newTargetMap(Map, ?> m) {
return newTargetMap(m, m == null ? 0 : m.size());
}
@SuppressWarnings("rawtypes")
static Map newTargetMap(Map, ?> m, int size) {
if (m == null) {
return new HashMap<>();
}
Map res = null;
if (HashMap.class.equals(m.getClass())) {
res = new HashMap<>(N.initHashCapacity(size));
} else if (m instanceof SortedMap) {
res = new TreeMap<>(((SortedMap) m).comparator());
} else if (m instanceof IdentityHashMap) {
res = new IdentityHashMap<>(N.initHashCapacity(size));
} else if (m instanceof LinkedHashMap) {
res = new LinkedHashMap<>(N.initHashCapacity(size));
} else if (m instanceof ImmutableMap) {
res = new LinkedHashMap<>(N.initHashCapacity(size));
} else {
try {
res = N.newInstance(m.getClass());
} catch (Exception e) {
res = new LinkedHashMap<>(N.initHashCapacity(size));
}
}
return res;
}
@SuppressWarnings("rawtypes")
static Map newOrderingMap(Map, ?> m) {
if (m == null) {
return new HashMap<>();
}
Map res = null;
if (HashMap.class.equals(m.getClass())) {
res = new HashMap<>(N.initHashCapacity(m.size()));
} else if (m instanceof SortedMap) {
res = new LinkedHashMap<>(N.initHashCapacity(m.size()));
} else if (m instanceof IdentityHashMap) {
res = new IdentityHashMap<>(N.initHashCapacity(m.size()));
} else if (m instanceof LinkedHashMap) {
res = new LinkedHashMap<>(N.initHashCapacity(m.size()));
} else if (m instanceof ImmutableMap) {
res = new LinkedHashMap<>(N.initHashCapacity(m.size()));
} else {
try {
res = N.newInstance(m.getClass());
} catch (Exception e) {
res = new LinkedHashMap<>(N.initHashCapacity(m.size()));
}
}
return res;
}
public static Nullable get(final Map map, final Object key) {
if (N.isNullOrEmpty(map)) {
return Nullable.empty();
}
final V val = map.get(key);
if (val != null || map.containsKey(key)) {
return Nullable.of(val);
} else {
return Nullable.empty();
}
}
/**
* Returns a list of values of the keys which exist in the specified Map
.
* If the key dosn't exist in the Map
, No value will be added into the returned list.
*
* @param map
* @param keys
* @return
*/
public static List getIfPresentForEach(final Map map, final Collection> keys) {
if (N.isNullOrEmpty(map) || N.isNullOrEmpty(keys)) {
return new ArrayList<>(0);
}
final List result = new ArrayList<>(keys.size());
V val = null;
for (Object key : keys) {
val = map.get(key);
if (val != null || map.containsKey(key)) {
result.add(val);
}
}
return result;
}
/**
* Returns the value to which the specified key is mapped, or
* {@code defaultValue} if this map contains no mapping for the key.
*
* @param map
* @param key
* @param defaultValue
* @return
*/
public static V getOrDefault(final Map map, final Object key, final V defaultValue) {
if (N.isNullOrEmpty(map)) {
return defaultValue;
}
final V val = map.get(key);
if (val != null || map.containsKey(key)) {
return val;
} else {
return defaultValue;
}
}
/**
* Returns the value to which the specified key is mapped, or
* an empty immutable {@code List} if this map contains no mapping for the key.
*
* @param map
* @param key
* @return
*/
public static > List getOrEmptyList(final Map map, final Object key) {
if (N.isNullOrEmpty(map)) {
return N. emptyList();
}
final V val = map.get(key);
if (val != null || map.containsKey(key)) {
return val;
} else {
return N.emptyList();
}
}
/**
* Returns the value to which the specified key is mapped, or
* an empty immutable {@code Set} if this map contains no mapping for the key.
*
* @param map
* @param key
* @return
*/
public static > Set getOrEmptySet(final Map map, final Object key) {
if (N.isNullOrEmpty(map)) {
return N. emptySet();
}
final V val = map.get(key);
if (val != null || map.containsKey(key)) {
return val;
} else {
return N.emptySet();
}
}
public static List getOrDefaultForEach(final Map map, final Collection> keys, final V defaultValue) {
if (N.isNullOrEmpty(keys)) {
return new ArrayList<>(0);
} else if (N.isNullOrEmpty(map)) {
return new ArrayList<>(Arrays.asList(Array.repeat(defaultValue, keys.size())));
}
final List result = new ArrayList<>(keys.size());
V val = null;
for (Object key : keys) {
val = map.get(key);
if (val != null || map.containsKey(key)) {
result.add(val);
} else {
result.add(defaultValue);
}
}
return result;
}
/**
* Returns the value associated with the specified {@code key} if it exists in the specified {@code map} contains, or the new put {@code List} if it's absent.
*
* @param map
* @param key
* @return
*/
public static List getAndPutListIfAbsent(final Map> map, final K key) {
List v = map.get(key);
if (v == null) {
v = new ArrayList<>();
v = map.put(key, v);
}
return v;
}
/**
* Returns the value associated with the specified {@code key} if it exists in the specified {@code map} contains, or the new put {@code Set} if it's absent.
*
* @param map
* @param key
* @return
*/
public static Set getAndPutSetIfAbsent(final Map> map, final K key) {
Set v = map.get(key);
if (v == null) {
v = new HashSet<>();
v = map.put(key, v);
}
return v;
}
/**
* Returns the value associated with the specified {@code key} if it exists in the specified {@code map} contains, or the new put {@code Set} if it's absent.
*
* @param map
* @param key
* @return
*/
public static Set getAndPutLinkedHashSetIfAbsent(final Map> map, final K key) {
Set v = map.get(key);
if (v == null) {
v = new LinkedHashSet<>();
v = map.put(key, v);
}
return v;
}
/**
* Returns the value associated with the specified {@code key} if it exists in the specified {@code map} contains, or the new put {@code Map} if it's absent.
*
* @param map
* @param key
* @return
*/
public static Map getAndPutMapIfAbsent(final Map> map, final K key) {
Map v = map.get(key);
if (v == null) {
v = new HashMap<>();
v = map.put(key, v);
}
return v;
}
/**
* Check if the specified Map
contains the specified Entry
*
* @param map
* @param entry
* @return
*/
public static boolean contains(final Map, ?> map, final Map.Entry, ?> entry) {
return contains(map, entry.getKey(), entry.getValue());
}
public static boolean contains(final Map, ?> map, final Object key, final Object value) {
if (N.isNullOrEmpty(map)) {
return false;
}
final Object val = map.get(key);
return val == null ? value == null && map.containsKey(key) : N.equals(val, value);
}
public static Map intersection(final Map map, final Map extends K, ? extends V> map2) {
if (N.isNullOrEmpty(map) || N.isNullOrEmpty(map2)) {
return new LinkedHashMap<>();
}
final Map result = map instanceof IdentityHashMap ? new IdentityHashMap() : new LinkedHashMap();
Object val = null;
for (Map.Entry entry : map.entrySet()) {
val = map2.get(entry.getKey());
if ((val != null && N.equals(val, entry.getValue())) || (entry.getValue() == null && map.containsKey(entry.getKey()))) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
public static Map>> difference(final Map map, final Map map2) {
if (N.isNullOrEmpty(map)) {
return new LinkedHashMap<>();
}
final Map>> result = map instanceof IdentityHashMap ? new IdentityHashMap>>()
: new LinkedHashMap>>();
if (N.isNullOrEmpty(map2)) {
for (Map.Entry entry : map.entrySet()) {
result.put(entry.getKey(), Pair.of(entry.getValue(), Nullable. empty()));
}
} else {
V val = null;
for (Map.Entry entry : map.entrySet()) {
val = map2.get(entry.getKey());
if (val == null && map2.containsKey(entry.getKey()) == false) {
result.put(entry.getKey(), Pair.of(entry.getValue(), Nullable. empty()));
} else if (N.equals(val, entry.getValue()) == false) {
result.put(entry.getKey(), Pair.of(entry.getValue(), Nullable.of(val)));
}
}
}
return result;
}
public static Map, Nullable>> symmetricDifference(final Map map, final Map map2) {
final boolean isIdentityHashMap = (N.notNullOrEmpty(map) && map instanceof IdentityHashMap)
|| (N.notNullOrEmpty(map2) && map2 instanceof IdentityHashMap);
final Map, Nullable>> result = isIdentityHashMap ? new IdentityHashMap, Nullable>>()
: new LinkedHashMap, Nullable>>();
if (N.notNullOrEmpty(map)) {
if (N.isNullOrEmpty(map2)) {
for (Map.Entry entry : map.entrySet()) {
result.put(entry.getKey(), Pair.of(Nullable.of(entry.getValue()), Nullable. empty()));
}
} else {
K key = null;
V val2 = null;
for (Map.Entry entry : map.entrySet()) {
key = entry.getKey();
val2 = map2.get(key);
if (val2 == null && map2.containsKey(key) == false) {
result.put(key, Pair.of(Nullable.of(entry.getValue()), Nullable. empty()));
} else if (N.equals(val2, entry.getValue()) == false) {
result.put(key, Pair.of(Nullable.of(entry.getValue()), Nullable.of(val2)));
}
}
}
}
if (N.notNullOrEmpty(map2)) {
if (N.isNullOrEmpty(map)) {
for (Map.Entry entry : map2.entrySet()) {
result.put(entry.getKey(), Pair.of(Nullable. empty(), Nullable.of(entry.getValue())));
}
} else {
for (Map.Entry entry : map2.entrySet()) {
if (map.containsKey(entry.getKey()) == false) {
result.put(entry.getKey(), Pair.of(Nullable. empty(), Nullable.of(entry.getValue())));
}
}
}
}
return result;
}
/**
* If the specified key is not already associated with a value (or is mapped
* to {@code null}) associates it with the given value and returns
* {@code null}, else returns the current value.
*
* @implSpec
* The default implementation is equivalent to, for this {@code
* map}:
*
* {@code
* V v = map.get(key);
* if (v == null)
* v = map.put(key, value);
*
* return v;
* }
*
* The default implementation makes no guarantees about synchronization
* or atomicity properties of this method. Any implementation providing
* atomicity guarantees must override this method and document its
* concurrency properties.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with the specified key, or
* {@code null} if there was no mapping for the key.
* (A {@code null} return can also indicate that the map
* previously associated {@code null} with the key,
* if the implementation supports null values.)
* @throws UnsupportedOperationException if the {@code put} operation
* is not supported by this map
* (optional)
* @throws ClassCastException if the key or value is of an inappropriate
* type for this map
* (optional)
* @throws NullPointerException if the specified map is null, or if the specified key or value is null,
* and this map does not permit null keys or values
* (optional)
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* (optional)
*/
public static V putIfAbsent(final Map map, K key, final V value) {
V v = map.get(key);
if (v == null) {
v = map.put(key, value);
}
return v;
}
public static V putIfAbsent(final Map map, K key, final Supplier supplier) {
V v = map.get(key);
if (v == null) {
v = map.put(key, supplier.get());
}
return v;
}
/**
* Removes the specified entry.
*
* @param map
* @param entry
* @return
*/
public static boolean remove(final Map map, Map.Entry, ?> entry) {
return remove(map, entry.getKey(), entry.getValue());
}
/**
* Removes the entry for the specified key only if it is currently
* mapped to the specified value.
*
* @implSpec
* The default implementation is equivalent to, for this {@code map}:
*
* {@code
* if (map.containsKey(key) && N.equals(map.get(key), value)) {
* map.remove(key);
* return true;
* } else
* return false;
* }
*
* The default implementation makes no guarantees about synchronization
* or atomicity properties of this method. Any implementation providing
* atomicity guarantees must override this method and document its
* concurrency properties.
*
* @param key key with which the specified value is associated
* @param value value expected to be associated with the specified key
* @return {@code true} if the value was removed
* @throws UnsupportedOperationException if the {@code remove} operation
* is not supported by this map
* (optional)
* @throws ClassCastException if the key or value is of an inappropriate
* type for this map
* (optional)
* @throws NullPointerException if the specified key or value is null,
* and this map does not permit null keys or values
* (optional)
* @since 1.8
*/
public static boolean remove(final Map map, final Object key, final Object value) {
if (N.isNullOrEmpty(map)) {
return false;
}
final Object curValue = map.get(key);
if (!N.equals(curValue, value) || (curValue == null && !map.containsKey(key))) {
return false;
}
map.remove(key);
return true;
}
/**
*
* @param map
* @param keysToRemove
* @return true
if any key/value was removed, otherwise false
.
*/
public static boolean removeKeys(final Map, ?> map, final Collection> keysToRemove) {
if (N.isNullOrEmpty(map) || N.isNullOrEmpty(keysToRemove)) {
return false;
}
final int originalSize = map.size();
for (Object key : keysToRemove) {
map.remove(key);
}
return map.size() < originalSize;
}
/**
* The the entries from the specified Map
*
* @param map
* @param entriesToRemove
* @return true
if any key/value was removed, otherwise false
.
*/
public static boolean removeEntries(final Map, ?> map, final Map, ?> entriesToRemove) {
if (N.isNullOrEmpty(map) || N.isNullOrEmpty(entriesToRemove)) {
return false;
}
final int originalSize = map.size();
for (Map.Entry, ?> entry : entriesToRemove.entrySet()) {
if (N.equals(map.get(entry.getKey()), entry.getValue())) {
map.remove(entry.getKey());
}
}
return map.size() < originalSize;
}
/**
* Removes entries from the specified {@code map} by the the specified {@code filter}.
*
* @param map
* @param filter
* @return {@code true} if there are one or more than one entries removed from the specified map.
* @throws E
*/
public static boolean removeIf(final Map map, final Try.Predicate super Map.Entry, E> filter) throws E {
List keysToRemove = null;
for (Map.Entry entry : map.entrySet()) {
if (filter.test(entry)) {
if (keysToRemove == null) {
keysToRemove = new ArrayList<>(7);
}
keysToRemove.add(entry.getKey());
}
}
if (N.notNullOrEmpty(keysToRemove)) {
for (K key : keysToRemove) {
map.remove(key);
}
return true;
}
return false;
}
/**
* Removes entries from the specified {@code map} by the the specified {@code filter}.
*
* @param map
* @param filter
* @return {@code true} if there are one or more than one entries removed from the specified map.
* @throws E
*/
public static boolean removeIfKey(final Map map, final Try.Predicate super K, E> filter) throws E {
List keysToRemove = null;
for (Map.Entry entry : map.entrySet()) {
if (filter.test(entry.getKey())) {
if (keysToRemove == null) {
keysToRemove = new ArrayList<>(7);
}
keysToRemove.add(entry.getKey());
}
}
if (N.notNullOrEmpty(keysToRemove)) {
for (K key : keysToRemove) {
map.remove(key);
}
return true;
}
return false;
}
/**
* Removes entries from the specified {@code map} by the the specified {@code filter}.
*
* @param map
* @param filter
* @return {@code true} if there are one or more than one entries removed from the specified map.
* @throws E
*/
public static boolean removeIfValue(final Map map, final Try.Predicate super V, E> filter) throws E {
List keysToRemove = null;
for (Map.Entry entry : map.entrySet()) {
if (filter.test(entry.getValue())) {
if (keysToRemove == null) {
keysToRemove = new ArrayList<>(7);
}
keysToRemove.add(entry.getKey());
}
}
if (N.notNullOrEmpty(keysToRemove)) {
for (K key : keysToRemove) {
map.remove(key);
}
return true;
}
return false;
}
/**
* Replaces the entry for the specified key only if currently
* mapped to the specified value.
*
* @implSpec
* The default implementation is equivalent to, for this {@code map}:
*
* {@code
* if (map.containsKey(key) && N.equals(map.get(key), value)) {
* map.put(key, newValue);
* return true;
* } else
* return false;
* }
*
* The default implementation does not throw NullPointerException
* for maps that do not support null values if oldValue is null unless
* newValue is also null.
*
* The default implementation makes no guarantees about synchronization
* or atomicity properties of this method. Any implementation providing
* atomicity guarantees must override this method and document its
* concurrency properties.
*
* @param key key with which the specified value is associated
* @param oldValue value expected to be associated with the specified key
* @param newValue value to be associated with the specified key
* @return {@code true} if the value was replaced
* @throws UnsupportedOperationException if the {@code put} operation
* is not supported by this map
* (optional)
* @throws ClassCastException if the class of a specified key or value
* prevents it from being stored in this map
* @throws NullPointerException if a specified key or newValue is null,
* and this map does not permit null keys or values
* @throws NullPointerException if oldValue is null and this map does not
* permit null values
* (optional)
* @throws IllegalArgumentException if some property of a specified key
* or value prevents it from being stored in this map
* @since 1.8
*/
public static boolean replace(final Map map, final K key, final V oldValue, final V newValue) {
if (N.isNullOrEmpty(map)) {
return false;
}
final Object curValue = map.get(key);
if (!N.equals(curValue, oldValue) || (curValue == null && !map.containsKey(key))) {
return false;
}
map.put(key, newValue);
return true;
}
/**
* Replaces the entry for the specified key only if it is
* currently mapped to some value.
*
* @implSpec
* The default implementation is equivalent to, for this {@code map}:
*
* {@code
* if (map.containsKey(key)) {
* return map.put(key, value);
* } else
* return null;
* }
*
* The default implementation makes no guarantees about synchronization
* or atomicity properties of this method. Any implementation providing
* atomicity guarantees must override this method and document its
* concurrency properties.
*
* @param key key with which the specified value is associated
* @param newValue value to be associated with the specified key
* @return the previous value associated with the specified key, or
* {@code null} if there was no mapping for the key.
* (A {@code null} return can also indicate that the map
* previously associated {@code null} with the key,
* if the implementation supports null values.)
* @throws UnsupportedOperationException if the {@code put} operation
* is not supported by this map
* (optional)
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* (optional)
* @throws NullPointerException if the specified key or value is null,
* and this map does not permit null keys or values
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* @since 1.8
*/
public static V replace(final Map map, final K key, final V newValue) {
if (N.isNullOrEmpty(map)) {
return null;
}
V curValue = null;
if (((curValue = map.get(key)) != null) || map.containsKey(key)) {
curValue = map.put(key, newValue);
}
return curValue;
}
/**
* Replaces each entry's value with the result of invoking the given
* function on that entry until all entries have been processed or the
* function throws an exception. Exceptions thrown by the function are
* relayed to the caller.
*
* @implSpec
* The default implementation is equivalent to, for this {@code map}:
*
{@code
* for (Map.Entry entry : map.entrySet())
* entry.setValue(function.apply(entry.getKey(), entry.getValue()));
* }
*
* The default implementation makes no guarantees about synchronization
* or atomicity properties of this method. Any implementation providing
* atomicity guarantees must override this method and document its
* concurrency properties.
*
* @param function the function to apply to each entry
* @throws UnsupportedOperationException if the {@code set} operation
* is not supported by this map's entry set iterator.
* @throws ClassCastException if the class of a replacement value
* prevents it from being stored in this map
* @throws NullPointerException if the specified function is null, or the
* specified replacement value is null, and this map does not permit null
* values
* @throws ClassCastException if a replacement value is of an inappropriate
* type for this map
* (optional)
* @throws NullPointerException if function or a replacement value is null,
* and this map does not permit null keys or values
* (optional)
* @throws IllegalArgumentException if some property of a replacement value
* prevents it from being stored in this map
* (optional)
* @throws ConcurrentModificationException if an entry is found to be
* removed during iteration
* @since 1.8
*/
public static void replaceAll(final Map map, final Try.BiFunction super K, ? super V, ? extends V, E> function)
throws E {
N.checkArgNotNull(function);
if (N.isNullOrEmpty(map)) {
return;
}
K k = null;
V v = null;
for (Map.Entry entry : map.entrySet()) {
try {
k = entry.getKey();
v = entry.getValue();
} catch (IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
// ise thrown from function is not a cme.
v = function.apply(k, v);
try {
entry.setValue(v);
} catch (IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
}
}
/**
* If the specified key is not already associated with a value (or is mapped
* to {@code null}), attempts to compute its value using the given mapping
* function and enters it into this map unless {@code null}.
*
* If the function returns {@code null} no mapping is recorded. If
* the function itself throws an (unchecked) exception, the
* exception is rethrown, and no mapping is recorded. The most
* common usage is to construct a new object serving as an initial
* mapped value or memoized result, as in:
*
*
{@code
* map.computeIfAbsent(key, k -> new Value(f(k)));
* }
*
* Or to implement a multi-value map, {@code Map>},
* supporting multiple values per key:
*
* {@code
* map.computeIfAbsent(key, k -> new HashSet()).add(v);
* }
*
*
* @implSpec
* The default implementation is equivalent to the following steps for this
* {@code map}, then returning the current value or {@code null} if now
* absent:
*
* {@code
* if (map.get(key) == null) {
* V newValue = mappingFunction.apply(key);
* if (newValue != null)
* map.put(key, newValue);
* }
* }
*
* The default implementation makes no guarantees about synchronization
* or atomicity properties of this method. Any implementation providing
* atomicity guarantees must override this method and document its
* concurrency properties. In particular, all implementations of
* subinterface {@link java.util.concurrent.ConcurrentMap} must document
* whether the function is applied once atomically only if the value is not
* present.
*
* @param key key with which the specified value is to be associated
* @param mappingFunction the function to compute a value
* @return the current (existing or computed) value associated with
* the specified key, or null if the computed value is null
* @throws NullPointerException if the specified map is null, or the specified key is null and
* this map does not support null keys, or the mappingFunction
* is null
* @throws UnsupportedOperationException if the {@code put} operation
* is not supported by this map
* (optional)
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* (optional)
* @since 1.8
*/
public static V computeIfAbsent(final Map map, final K key, final Try.Function super K, ? extends V, E> mappingFunction)
throws E {
N.checkArgNotNull(mappingFunction);
V v = null;
if ((v = map.get(key)) == null) {
V newValue = null;
if ((newValue = mappingFunction.apply(key)) != null) {
map.put(key, newValue);
return newValue;
}
}
return v;
}
/**
* If the value for the specified key is present and non-null, attempts to
* compute a new mapping given the key and its current mapped value.
*
* If the function returns {@code null}, the mapping is removed. If the
* function itself throws an (unchecked) exception, the exception is
* rethrown, and the current mapping is left unchanged.
*
* @implSpec
* The default implementation is equivalent to performing the following
* steps for this {@code map}, then returning the current value or
* {@code null} if now absent:
*
*
{@code
* if (map.get(key) != null) {
* V oldValue = map.get(key);
* V newValue = remappingFunction.apply(key, oldValue);
* if (newValue != null)
* map.put(key, newValue);
* else
* map.remove(key);
* }
* }
*
* The default implementation makes no guarantees about synchronization
* or atomicity properties of this method. Any implementation providing
* atomicity guarantees must override this method and document its
* concurrency properties. In particular, all implementations of
* subinterface {@link java.util.concurrent.ConcurrentMap} must document
* whether the function is applied once atomically only if the value is not
* present.
*
* @param key key with which the specified value is to be associated
* @param remappingFunction the function to compute a value
* @return the new value associated with the specified key, or null if none
* @throws NullPointerException if the specified map is null, or the specified key is null and
* this map does not support null keys, or the
* remappingFunction is null
* @throws UnsupportedOperationException if the {@code put} operation
* is not supported by this map
* (optional)
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* (optional)
* @since 1.8
*/
public static V computeIfPresent(final Map map, K key,
final Try.BiFunction super K, ? super V, ? extends V, E> remappingFunction) throws E {
N.checkArgNotNull(remappingFunction);
V oldValue = null;
if ((oldValue = map.get(key)) != null) {
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null) {
map.put(key, newValue);
return newValue;
} else {
map.remove(key);
return null;
}
} else {
return null;
}
}
/**
* Attempts to compute a mapping for the specified key and its current
* mapped value (or {@code null} if there is no current mapping). For
* example, to either create or append a {@code String} msg to a value
* mapping:
*
* {@code
* map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))}
* (Method {@link #merge merge()} is often simpler to use for such purposes.)
*
* If the function returns {@code null}, the mapping is removed (or
* remains absent if initially absent). If the function itself throws an
* (unchecked) exception, the exception is rethrown, and the current mapping
* is left unchanged.
*
* @implSpec
* The default implementation is equivalent to performing the following
* steps for this {@code map}, then returning the current value or
* {@code null} if absent:
*
*
{@code
* V oldValue = map.get(key);
* V newValue = remappingFunction.apply(key, oldValue);
* if (oldValue != null ) {
* if (newValue != null)
* map.put(key, newValue);
* else
* map.remove(key);
* } else {
* if (newValue != null)
* map.put(key, newValue);
* else
* return null;
* }
* }
*
* The default implementation makes no guarantees about synchronization
* or atomicity properties of this method. Any implementation providing
* atomicity guarantees must override this method and document its
* concurrency properties. In particular, all implementations of
* subinterface {@link java.util.concurrent.ConcurrentMap} must document
* whether the function is applied once atomically only if the value is not
* present.
*
* @param key key with which the specified value is to be associated
* @param remappingFunction the function to compute a value
* @return the new value associated with the specified key, or null if none
* @throws NullPointerException if the specified map is null, or the specified key is null and
* this map does not support null keys, or the
* remappingFunction is null
* @throws UnsupportedOperationException if the {@code put} operation
* is not supported by this map
* (optional)
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* (optional)
* @since 1.8
*/
public static V compute(final Map map, K key,
final Try.BiFunction super K, ? super V, ? extends V, E> remappingFunction) throws E {
N.checkArgNotNull(remappingFunction);
V oldValue = map.get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (newValue == null) {
// delete mapping
if (oldValue != null || map.containsKey(key)) {
// something to remove
map.remove(key);
return null;
} else {
// nothing to do. Leave things as they were.
return null;
}
} else {
// add or replace old mapping
map.put(key, newValue);
return newValue;
}
}
/**
* If the specified key is not already associated with a value or is
* associated with null, associates it with the given non-null value.
* Otherwise, replaces the associated value with the results of the given
* remapping function, or removes if the result is {@code null}. This
* method may be of use when combining multiple mapped values for a key.
* For example, to either create or append a {@code String msg} to a
* value mapping:
*
* {@code
* map.merge(key, msg, String::concat)
* }
*
* If the function returns {@code null} the mapping is removed. If the
* function itself throws an (unchecked) exception, the exception is
* rethrown, and the current mapping is left unchanged.
*
* @implSpec
* The default implementation is equivalent to performing the following
* steps for this {@code map}, then returning the current value or
* {@code null} if absent:
*
*
{@code
* V oldValue = map.get(key);
* V newValue = (oldValue == null) ? value :
* remappingFunction.apply(oldValue, value);
* if (newValue == null)
* map.remove(key);
* else
* map.put(key, newValue);
* }
*
* The default implementation makes no guarantees about synchronization
* or atomicity properties of this method. Any implementation providing
* atomicity guarantees must override this method and document its
* concurrency properties. In particular, all implementations of
* subinterface {@link java.util.concurrent.ConcurrentMap} must document
* whether the function is applied once atomically only if the value is not
* present.
*
* @param key key with which the resulting value is to be associated
* @param value the non-null value to be merged with the existing value
* associated with the key or, if no existing value or a null value
* is associated with the key, to be associated with the key
* @param remappingFunction the function to recompute a value if present
* @return the new value associated with the specified key, or null if no
* value is associated with the key
* @throws UnsupportedOperationException if the {@code put} operation
* is not supported by this map
* (optional)
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* (optional)
* @throws NullPointerException if the specified map is null, or the specified key is null and this map
* does not support null keys or the value or remappingFunction is
* null
* @since 1.8
*/
public static V merge(final Map map, final K key, final V value,
final Try.BiFunction super V, ? super V, ? extends V, E> remappingFunction) throws E {
N.checkArgNotNull(remappingFunction);
N.checkArgNotNull(value);
V oldValue = map.get(key);
V newValue = (oldValue == null) ? value : remappingFunction.apply(oldValue, value);
if (newValue == null) {
map.remove(key);
} else {
map.put(key, newValue);
}
return newValue;
}
/**
* Performs the given action for each entry in this map until all entries
* have been processed or the action throws an exception. Unless
* otherwise specified by the implementing class, actions are performed in
* the order of entry set iteration (if an iteration order is specified.)
* Exceptions thrown by the action are relayed to the caller.
*
* @implSpec
* The default implementation is equivalent to, for this {@code map}:
* {@code
* for (Map.Entry entry : map.entrySet())
* action.accept(entry.getKey(), entry.getValue());
* }
*
* The default implementation makes no guarantees about synchronization
* or atomicity properties of this method. Any implementation providing
* atomicity guarantees must override this method and document its
* concurrency properties.
*
* @param action The action to be performed for each entry
* @throws NullPointerException if the specified action is null
* @throws ConcurrentModificationException if an entry is found to be
* removed during iteration
* @since 1.8
*/
public static void forEach(final Map map, final Try.BiConsumer super K, ? super V, E> action) throws E {
N.checkArgNotNull(action);
if (N.isNullOrEmpty(map)) {
return;
}
K k = null;
V v = null;
for (Map.Entry entry : map.entrySet()) {
try {
k = entry.getKey();
v = entry.getValue();
} catch (IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}
public static Map filter(final Map map, final Try.BiPredicate super K, ? super V, E> predicate) throws E {
if (map == null) {
return new HashMap();
}
final Map result = newTargetMap(map, 0);
for (Map.Entry entry : map.entrySet()) {
if (predicate.test(entry.getKey(), entry.getValue())) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
public static Map filterByKey(final Map map, final Try.Predicate super K, E> predicate) throws E {
if (map == null) {
return new HashMap();
}
final Map result = newTargetMap(map, 0);
for (Map.Entry entry : map.entrySet()) {
if (predicate.test(entry.getKey())) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
public static Map filterByValue(final Map map, final Try.Predicate super V, E> predicate) throws E {
if (map == null) {
return new HashMap();
}
final Map result = newTargetMap(map, 0);
for (Map.Entry entry : map.entrySet()) {
if (predicate.test(entry.getValue())) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
/**
*
* @param map
* @return
* @see Multimap#invertFrom(Map, com.landawn.abacus.util.function.Supplier)
* @see ListMultimap#invertFrom(Map)
* @see ListMultimap#invertFrom(Map)
*/
public static Map invert(final Map map) {
if (map == null) {
return new HashMap();
}
final Map result = newOrderingMap(map);
for (Map.Entry entry : map.entrySet()) {
result.put(entry.getValue(), entry.getKey());
}
return result;
}
/**
*
* @param map
* @return
* @see Multimap#flatInvertFrom(Map, com.landawn.abacus.util.function.Supplier)
* @see ListMultimap#flatInvertFrom(Map)
* @see SetMultimap#flatInvertFrom(Map)
*/
public static Map> flatInvert(final Map> map) {
if (map == null) {
return new HashMap>();
}
final Map> result = newOrderingMap(map);
for (Map.Entry> entry : map.entrySet()) {
final Collection extends V> c = entry.getValue();
if (N.notNullOrEmpty(c)) {
for (V v : c) {
List list = result.get(v);
if (list == null) {
list = new ArrayList<>();
result.put(v, list);
}
list.add(entry.getKey());
}
}
}
return result;
}
public static T map2Entity(final Class targetClass, final Map m) {
return map2Entity(targetClass, m, false, true);
}
@SuppressWarnings("unchecked")
public static T map2Entity(final Class targetClass, final Map m, final boolean ignoreNullProperty,
final boolean ignoreUnknownProperty) {
checkEntityClass(targetClass);
final T entity = N.newInstance(targetClass);
String propName = null;
Object propValue = null;
Method propSetMethod = null;
Class> paramClass = null;
for (Map.Entry entry : m.entrySet()) {
propName = entry.getKey();
propValue = entry.getValue();
if (ignoreNullProperty && (propValue == null)) {
continue;
}
propSetMethod = ClassUtil.getPropSetMethod(targetClass, propName);
if (propSetMethod == null) {
ClassUtil.setPropValue(entity, propName, propValue, ignoreUnknownProperty);
} else {
paramClass = propSetMethod.getParameterTypes()[0];
if (propValue != null && N.typeOf(propValue.getClass()).isMap() && N.isEntity(paramClass)) {
ClassUtil.setPropValue(entity, propSetMethod,
map2Entity(paramClass, (Map) propValue, ignoreNullProperty, ignoreUnknownProperty));
} else {
ClassUtil.setPropValue(entity, propSetMethod, propValue);
}
}
}
return entity;
}
public static T map2Entity(final Class targetClass, final Map m, final Collection selectPropNames) {
checkEntityClass(targetClass);
final T entity = N.newInstance(targetClass);
Object propValue = null;
Method propSetMethod = null;
Class> paramClass = null;
for (String propName : selectPropNames) {
propValue = m.get(propName);
if (propValue == null && m.containsKey(propName) == false) {
throw new IllegalArgumentException("Property name: " + propName + " is not found in map with key set: " + m.keySet());
}
propSetMethod = ClassUtil.getPropSetMethod(targetClass, propName);
if (propSetMethod == null) {
ClassUtil.setPropValue(entity, propName, propValue, false);
} else {
paramClass = propSetMethod.getParameterTypes()[0];
if (propValue != null && N.typeOf(propValue.getClass()).isMap() && N.isEntity(paramClass)) {
ClassUtil.setPropValue(entity, propSetMethod, map2Entity(paramClass, (Map) propValue));
} else {
ClassUtil.setPropValue(entity, propSetMethod, propValue);
}
}
}
return entity;
}
public static List map2Entity(final Class targetClass, final Collection