All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.landawn.abacus.util.Maps Maven / Gradle / Ivy

Go to download

A general programming library in Java/Android. It's easy to learn and simple to use with concise and powerful APIs.

There is a newer version: 5.2.4
Show newest version
/*
 * Copyright (C) 2019 HaiYang Li
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.landawn.abacus.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Supplier;

import com.landawn.abacus.parser.ParserUtil;
import com.landawn.abacus.parser.ParserUtil.BeanInfo;
import com.landawn.abacus.parser.ParserUtil.PropInfo;
import com.landawn.abacus.type.Type;
import com.landawn.abacus.util.Fn.IntFunctions;
import com.landawn.abacus.util.Fn.Suppliers;
import com.landawn.abacus.util.u.Nullable;
import com.landawn.abacus.util.u.Optional;
import com.landawn.abacus.util.u.OptionalBoolean;
import com.landawn.abacus.util.u.OptionalByte;
import com.landawn.abacus.util.u.OptionalChar;
import com.landawn.abacus.util.u.OptionalDouble;
import com.landawn.abacus.util.u.OptionalFloat;
import com.landawn.abacus.util.u.OptionalInt;
import com.landawn.abacus.util.u.OptionalLong;
import com.landawn.abacus.util.u.OptionalShort;

/**
 * 

* Note: This class includes codes copied from Apache Commons Lang, Google Guava and other open source projects under the Apache License 2.0. * The methods copied from other libraries/frameworks/projects may be modified in this class. *

* * @see com.landawn.abacus.util.N * @see com.landawn.abacus.util.Iterables * @see com.landawn.abacus.util.Iterators * @see com.landawn.abacus.util.Strings */ public final class Maps { private Maps() { // Utility class. } /** * * @param * @param the key type * @param c * @param keyMapper * @return */ public static Map create(Collection c, final Function keyMapper) { N.checkArgNotNull(keyMapper); if (N.isNullOrEmpty(c)) { return new HashMap<>(); } final Map result = N.newHashMap(c.size()); for (T e : c) { result.put(keyMapper.apply(e), e); } return result; } /** * * @param * @param the key type * @param the value type * @param c * @param keyMapper * @param valueExtractor * @return */ public static Map create(Collection c, final Function keyMapper, final Function valueExtractor) { N.checkArgNotNull(keyMapper); N.checkArgNotNull(valueExtractor); if (N.isNullOrEmpty(c)) { return new HashMap<>(); } final Map result = N.newHashMap(c.size()); for (T e : c) { result.put(keyMapper.apply(e), valueExtractor.apply(e)); } return result; } /** * * @param * @param the key type * @param the value type * @param * @param c * @param keyMapper * @param valueExtractor * @param mapSupplier * @return */ public static > M create(Collection c, final Function keyMapper, final Function valueExtractor, final IntFunction mapSupplier) { N.checkArgNotNull(keyMapper); N.checkArgNotNull(valueExtractor); N.checkArgNotNull(mapSupplier); if (N.isNullOrEmpty(c)) { return mapSupplier.apply(0); } final M result = mapSupplier.apply(c.size()); for (T e : c) { result.put(keyMapper.apply(e), valueExtractor.apply(e)); } return result; } /** * * @param * @param * @param * @param * @param c * @param keyMapper * @param valueExtractor * @param mergeFunction * @param mapSupplier * @return */ public static > M create(Collection c, final Function keyMapper, final Function valueExtractor, final BinaryOperator mergeFunction, final IntFunction mapSupplier) { N.checkArgNotNull(keyMapper); N.checkArgNotNull(valueExtractor); N.checkArgNotNull(mergeFunction); N.checkArgNotNull(mapSupplier); if (N.isNullOrEmpty(c)) { return mapSupplier.apply(0); } final M result = mapSupplier.apply(c.size()); K key = null; for (T e : c) { key = keyMapper.apply(e); final V oldValue = result.get(key); if (oldValue == null && !result.containsKey(key)) { result.put(key, valueExtractor.apply(e)); } else { result.put(key, mergeFunction.apply(oldValue, valueExtractor.apply(e))); } } return result; } /** * * @param * @param the key type * @param iter * @param keyMapper * @return */ public static Map create(final Iterator iter, final Function keyMapper) { N.checkArgNotNull(keyMapper); if (iter == null) { return new HashMap<>(); } final Map result = new HashMap<>(); T e = null; while (iter.hasNext()) { e = iter.next(); result.put(keyMapper.apply(e), e); } return result; } /** * * @param * @param the key type * @param the value type * @param iter * @param keyMapper * @param valueExtractor * @return */ public static Map create(final Iterator iter, final Function keyMapper, final Function valueExtractor) { N.checkArgNotNull(keyMapper); N.checkArgNotNull(valueExtractor); if (iter == null) { return new HashMap<>(); } final Map result = new HashMap<>(); T e = null; while (iter.hasNext()) { e = iter.next(); result.put(keyMapper.apply(e), valueExtractor.apply(e)); } return result; } /** * * @param * @param the key type * @param the value type * @param * @param iter * @param keyMapper * @param valueExtractor * @param mapSupplier * @return */ public static > M create(final Iterator iter, final Function keyMapper, final Function valueExtractor, final Supplier mapSupplier) { N.checkArgNotNull(keyMapper); N.checkArgNotNull(valueExtractor); N.checkArgNotNull(mapSupplier); if (iter == null) { return mapSupplier.get(); } final M result = mapSupplier.get(); T e = null; while (iter.hasNext()) { e = iter.next(); result.put(keyMapper.apply(e), valueExtractor.apply(e)); } return result; } /** * * @param * @param * @param * @param * @param iter * @param keyMapper * @param valueExtractor * @param mergeFunction * @param mapSupplier * @return */ public static > M create(final Iterator iter, final Function keyMapper, final Function valueExtractor, final BinaryOperator mergeFunction, final Supplier mapSupplier) { N.checkArgNotNull(keyMapper); N.checkArgNotNull(valueExtractor); N.checkArgNotNull(mergeFunction); N.checkArgNotNull(mapSupplier); if (iter == null) { return mapSupplier.get(); } final M result = mapSupplier.get(); T e = null; K key = null; while (iter.hasNext()) { e = iter.next(); key = keyMapper.apply(e); final V oldValue = result.get(key); if (oldValue == null && !result.containsKey(key)) { result.put(key, valueExtractor.apply(e)); } else { result.put(key, mergeFunction.apply(oldValue, valueExtractor.apply(e))); } } return result; } /** * * @param * @param * @param * @param map * @param valueMapper * @return */ public static Map create(final Map map, final Function valueMapper) { N.checkArgNotNull(valueMapper); if (map == null) { return new HashMap<>(); } final Map result = Maps.newTargetMap(map); for (Map.Entry entry : map.entrySet()) { result.put(entry.getKey(), valueMapper.apply(entry.getValue())); } return result; } /** * * @param * @param * @param * @param * @param map * @param valueMapper * @param mapSupplier * @return */ public static > M create(final Map map, final Function valueMapper, final IntFunction mapSupplier) { N.checkArgNotNull(valueMapper); N.checkArgNotNull(mapSupplier); if (map == null) { return mapSupplier.apply(0); } final M result = mapSupplier.apply(map.size()); for (Map.Entry entry : map.entrySet()) { result.put(entry.getKey(), valueMapper.apply(entry.getValue())); } return result; } /** * * * @param * @param the key type * @param c * @param keyMapper * @return * @deprecated Use {@link #create(Collection,Function)} instead */ @Deprecated public static Map newMap(Collection c, final Function keyMapper) { return create(c, keyMapper); } /** * * * @param * @param the key type * @param the value type * @param c * @param keyMapper * @param valueExtractor * @return * @deprecated Use {@link #create(Collection,Function,Function)} instead */ @Deprecated public static Map newMap(Collection c, final Function keyMapper, final Function valueExtractor) { return create(c, keyMapper, valueExtractor); } /** * * * @param * @param the key type * @param the value type * @param * @param c * @param keyMapper * @param valueExtractor * @param mapSupplier * @return * @deprecated Use {@link #create(Collection,Function,Function,IntFunction)} instead */ @Deprecated public static > M newMap(Collection c, final Function keyMapper, final Function valueExtractor, final IntFunction mapSupplier) { return create(c, keyMapper, valueExtractor, mapSupplier); } /** * * * @param * @param * @param * @param * @param c * @param keyMapper * @param valueExtractor * @param mergeFunction * @param mapSupplier * @return * @deprecated Use {@link #create(Collection,Function,Function,BinaryOperator,IntFunction)} instead */ @Deprecated public static > M newMap(Collection c, final Function keyMapper, final Function valueExtractor, final BinaryOperator mergeFunction, final IntFunction mapSupplier) { return create(c, keyMapper, valueExtractor, mergeFunction, mapSupplier); } /** * * * @param * @param the key type * @param iter * @param keyMapper * @return * @deprecated Use {@link #create(Iterator,Throwables.Function)} instead */ @Deprecated public static Map newMap(final Iterator iter, final Function keyMapper) { return create(iter, keyMapper); } /** * * * @param * @param the key type * @param the value type * @param iter * @param keyMapper * @param valueExtractor * @return * @deprecated Use {@link #create(Iterator,Throwables.Function,Function)} instead */ @Deprecated public static Map newMap(final Iterator iter, final Function keyMapper, final Function valueExtractor) { return create(iter, keyMapper, valueExtractor); } /** * * * @param * @param the key type * @param the value type * @param * @param iter * @param keyMapper * @param valueExtractor * @param mapSupplier * @return * @deprecated Use {@link #create(Iterator,Throwables.Function,Function,Supplier)} instead */ @Deprecated public static > M newMap(final Iterator iter, final Function keyMapper, final Function valueExtractor, final Supplier mapSupplier) { return create(iter, keyMapper, valueExtractor, mapSupplier); } /** * * * @param * @param * @param * @param * @param iter * @param keyMapper * @param valueExtractor * @param mergeFunction * @param mapSupplier * @return * @deprecated Use {@link #create(Iterator,Throwables.Function,Function,BinaryOperator,Supplier)} instead */ @Deprecated public static > M newMap(final Iterator iter, final Function keyMapper, final Function valueExtractor, final BinaryOperator mergeFunction, final Supplier mapSupplier) { return create(iter, keyMapper, valueExtractor, mergeFunction, mapSupplier); } /** * * @param * @param * @param key * @param value * @return * @deprecated replaced by {@link N#newEntry(Object, Object)} */ @Deprecated public static Map.Entry newEntry(final K key, final V value) { return N.newEntry(key, value); } /** * * @param * @param * @param key * @param value * @return * @deprecated replaced by {@link N#newImmutableEntry(Object, Object)} */ @Deprecated public static ImmutableEntry newImmutableEntry(final K key, final V value) { return N.newImmutableEntry(key, value); } /** * New target map. * * @param m * @return */ @SuppressWarnings("rawtypes") static Map newTargetMap(Map m) { return newTargetMap(m, m == null ? 0 : m.size()); } /** * New target map. * * @param m * @param size * @return */ @SuppressWarnings("rawtypes") static Map newTargetMap(Map m, int size) { if (m == null) { return size == 0 ? new HashMap<>() : new HashMap<>(size); } if (m instanceof SortedMap) { return new TreeMap<>(((SortedMap) m).comparator()); } return N.newMap(m.getClass(), size); } /** * New ordering map. * * @param m * @return */ @SuppressWarnings("rawtypes") static Map newOrderingMap(Map m) { if (m == null) { return new HashMap<>(); } return N.newMap(m.getClass(), m.size()); } /** * * * @param * @param * @param keys * @param values * @return */ public static Map zip(final Collection keys, final Collection values) { if (N.isNullOrEmpty(keys) || N.isNullOrEmpty(values)) { return new HashMap<>(); } final Iterator keyIter = keys.iterator(); final Iterator valueIter = values.iterator(); final int minLen = N.min(keys.size(), values.size()); final Map result = N.newHashMap(minLen); for (int i = 0; i < minLen; i++) { result.put(keyIter.next(), valueIter.next()); } return result; } /** * * * @param * @param * @param * @param keys * @param values * @param mapSupplier * @return */ public static > Map zip(final Collection keys, final Collection values, final IntFunction mapSupplier) { if (N.isNullOrEmpty(keys) || N.isNullOrEmpty(values)) { return new HashMap<>(); } final Iterator keyIter = keys.iterator(); final Iterator valueIter = values.iterator(); final int minLen = N.min(keys.size(), values.size()); final Map result = mapSupplier.apply(minLen); for (int i = 0; i < minLen; i++) { result.put(keyIter.next(), valueIter.next()); } return result; } /** * * * @param * @param * @param * @param keys * @param values * @param mergeFunction * @param mapSupplier * @return */ public static > Map zip(final Collection keys, final Collection values, final BinaryOperator mergeFunction, final IntFunction mapSupplier) { if (N.isNullOrEmpty(keys) || N.isNullOrEmpty(values)) { return new HashMap<>(); } final Iterator keyIter = keys.iterator(); final Iterator valueIter = values.iterator(); final int minLen = N.min(keys.size(), values.size()); final Map result = mapSupplier.apply(minLen); for (int i = 0; i < minLen; i++) { result.merge(keyIter.next(), valueIter.next(), mergeFunction); } return result; } /** * * @param the key type * @param the value type * @param map * @param key * @return */ public static Nullable get(final Map map, final K 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 the value to which the specified key is mapped, or {@code defaultValue} if this map contains no mapping for the key. * * @param the key type * @param the value type * @param map * @param key * @param defaultValue * @return */ public static V getOrDefault(final Map map, final K 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 if it's not {@code null}, * or {@code defaultForNull} if this map contains no mapping for the key or it's {@code null}. * * @param * @param * @param map * @param key * @param defaultForNull to return if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * @return */ public static V getOrDefaultIfNull(final Map map, final K key, final V defaultForNull) { if (N.isNullOrEmpty(map)) { return defaultForNull; } final V val = map.get(key); if (val == null) { return defaultForNull; } else { return val; } } /** * Returns an empty {@code OptionalBoolean} if the specified {@code map} is empty, or no value found by the specified {@code key}, or the value is {@code null}. * * @param * @param map * @param key * @return */ public static OptionalBoolean getBoolean(final Map map, final K key) { if (N.isNullOrEmpty(map)) { return OptionalBoolean.empty(); } final Object val = map.get(key); if (val == null) { return OptionalBoolean.empty(); } else if (val instanceof Boolean) { return OptionalBoolean.of((Boolean) val); } else { return OptionalBoolean.of(N.parseBoolean(N.toString(val))); } } /** * Returns the mapped {@code boolean} or a boolean converted from String. * {@code defaultForNull} is returned if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * * @param * @param map * @param key * @param defaultForNull to return if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * @return */ public static boolean getBoolean(final Map map, final K key, final boolean defaultForNull) { if (N.isNullOrEmpty(map)) { return defaultForNull; } final Object val = map.get(key); if (val == null) { return defaultForNull; } else if (val instanceof Boolean) { return (Boolean) val; } else { return N.parseBoolean(N.toString(val)); } } /** * Returns an empty {@code OptionalChar} if the specified {@code map} is empty, or no value found by the specified {@code key}, or the value is {@code null}. * * @param * @param map * @param key * @return */ public static OptionalChar getChar(final Map map, final K key) { if (N.isNullOrEmpty(map)) { return OptionalChar.empty(); } final Object val = map.get(key); if (val == null) { return OptionalChar.empty(); } else if (val instanceof Character) { return OptionalChar.of(((Character) val)); } else { return OptionalChar.of(N.parseChar(N.toString(val))); } } /** * Returns the mapped {@code char} or a char converted from String. * {@code defaultForNull} is returned if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * * @param * @param map * @param key * @param defaultForNull to return if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * @return */ public static char getChar(final Map map, final K key, final char defaultForNull) { if (N.isNullOrEmpty(map)) { return defaultForNull; } final Object val = map.get(key); if (val == null) { return defaultForNull; } else if (val instanceof Character) { return (Character) val; } else { return N.parseChar(N.toString(val)); } } /** * Returns an empty {@code OptionalByte} if the specified {@code map} is empty, or no value found by the specified {@code key}, or the value is {@code null}. * * @param * @param map * @param key * @return */ public static OptionalByte getByte(final Map map, final K key) { if (N.isNullOrEmpty(map)) { return OptionalByte.empty(); } final Object val = map.get(key); if (val == null) { return OptionalByte.empty(); } else if (val instanceof Number) { return OptionalByte.of(((Number) val).byteValue()); } else { return OptionalByte.of(Numbers.toByte(N.toString(val))); } } /** * Returns the mapped {@code byte} or a byte converted from String. * {@code defaultForNull} is returned if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * * @param * @param map * @param key * @param defaultForNull to return if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * @return */ public static byte getByte(final Map map, final K key, final byte defaultForNull) { if (N.isNullOrEmpty(map)) { return defaultForNull; } final Object val = map.get(key); if (val == null) { return defaultForNull; } else if (val instanceof Number) { return ((Number) val).byteValue(); } else { return Numbers.toByte(N.toString(val)); } } /** * Returns an empty {@code OptionalShort} if the specified {@code map} is empty, or no value found by the specified {@code key}, or the value is {@code null}. * * @param * @param map * @param key * @return */ public static OptionalShort getShort(final Map map, final K key) { if (N.isNullOrEmpty(map)) { return OptionalShort.empty(); } final Object val = map.get(key); if (val == null) { return OptionalShort.empty(); } else if (val instanceof Number) { return OptionalShort.of(((Number) val).shortValue()); } else { return OptionalShort.of(Numbers.toShort(N.toString(val))); } } /** * Returns the mapped {@code short} or a short converted from String. * {@code defaultForNull} is returned if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * * @param * @param map * @param key * @param defaultForNull to return if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * @return */ public static short getShort(final Map map, final K key, final short defaultForNull) { if (N.isNullOrEmpty(map)) { return defaultForNull; } final Object val = map.get(key); if (val == null) { return defaultForNull; } else if (val instanceof Number) { return ((Number) val).shortValue(); } else { return Numbers.toShort(N.toString(val)); } } /** * Returns an empty {@code OptionalInt} if the specified {@code map} is empty, or no value found by the specified {@code key}, or the value is {@code null}. * * @param * @param map * @param key * @return */ public static OptionalInt getInt(final Map map, final K key) { if (N.isNullOrEmpty(map)) { return OptionalInt.empty(); } final Object val = map.get(key); if (val == null) { return OptionalInt.empty(); } else if (val instanceof Number) { return OptionalInt.of(((Number) val).intValue()); } else { return OptionalInt.of(Numbers.toInt(N.toString(val))); } } /** * Returns the mapped {@code integer} or an integer converted from String. * {@code defaultForNull} is returned if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * * @param * @param map * @param key * @param defaultForNull to return if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * @return */ public static int getInt(final Map map, final K key, final int defaultForNull) { if (N.isNullOrEmpty(map)) { return defaultForNull; } final Object val = map.get(key); if (val == null) { return defaultForNull; } else if (val instanceof Number) { return ((Number) val).intValue(); } else { return Numbers.toInt(N.toString(val)); } } /** * Returns an empty {@code OptionalLong} if the specified {@code map} is empty, or no value found by the specified {@code key}, or the value is {@code null}. * * @param * @param map * @param key * @return */ public static OptionalLong getLong(final Map map, final K key) { if (N.isNullOrEmpty(map)) { return OptionalLong.empty(); } final Object val = map.get(key); if (val == null) { return OptionalLong.empty(); } else if (val instanceof Number) { return OptionalLong.of(((Number) val).longValue()); } else { return OptionalLong.of(Numbers.toLong(N.toString(val))); } } /** * Returns the mapped {@code long} or a long converted from String. * {@code defaultForNull} is returned if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * * @param * @param map * @param key * @param defaultForNull to return if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * @return */ public static long getLong(final Map map, final K key, final long defaultForNull) { if (N.isNullOrEmpty(map)) { return defaultForNull; } final Object val = map.get(key); if (val == null) { return defaultForNull; } else if (val instanceof Number) { return ((Number) val).longValue(); } else { return Numbers.toLong(N.toString(val)); } } /** * Returns an empty {@code OptionalFloat} if the specified {@code map} is empty, or no value found by the specified {@code key}, or the value is {@code null}. * * @param * @param map * @param key * @return */ public static OptionalFloat getFloat(final Map map, final K key) { if (N.isNullOrEmpty(map)) { return OptionalFloat.empty(); } final Object val = map.get(key); if (val == null) { return OptionalFloat.empty(); } else { return OptionalFloat.of(Numbers.toFloat(val)); } } /** * Returns the mapped {@code float} or a float converted from String. * {@code defaultForNull} is returned if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * * @param * @param map * @param key * @param defaultForNull to return if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * @return */ public static float getFloat(final Map map, final K key, final float defaultForNull) { if (N.isNullOrEmpty(map)) { return defaultForNull; } final Object val = map.get(key); if (val == null) { return defaultForNull; } else { return Numbers.toFloat(val); } } /** * Returns an empty {@code OptionalDouble} if the specified {@code map} is empty, or no value found by the specified {@code key}, or the value is {@code null}. * * @param * @param map * @param key * @return */ public static OptionalDouble getDouble(final Map map, final K key) { if (N.isNullOrEmpty(map)) { return OptionalDouble.empty(); } final Object val = map.get(key); if (val == null) { return OptionalDouble.empty(); } else { return OptionalDouble.of(Numbers.toDouble(val)); } } /** * Returns the mapped {@code double} or a double converted from String. * {@code defaultForNull} is returned if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * * @param * @param map * @param key * @param defaultForNull to return if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * @return */ public static double getDouble(final Map map, final K key, final double defaultForNull) { if (N.isNullOrEmpty(map)) { return defaultForNull; } final Object val = map.get(key); if (val == null) { return defaultForNull; } else { return Numbers.toDouble(val); } } /** * Returns an empty {@code Optional} if the specified {@code map} is empty, or no value found by the specified {@code key}, or the value is {@code null}. * * @param * @param map * @param key * @return */ public static Optional getString(final Map map, final K key) { if (N.isNullOrEmpty(map)) { return Optional.empty(); } final Object val = map.get(key); if (val == null) { return Optional.empty(); } else if (val instanceof String) { return Optional.of((String) val); } else { return Optional.of(N.stringOf(val)); } } /** * Returns the mapped {@code String} or a {@code String} converted from {@code N.toString(value)}. * {@code defaultForNull} is returned if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * * @param * @param map * @param key * @param defaultForNull to return if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * @return */ public static String getString(final Map map, final K key, final String defaultForNull) { N.checkArgNotNull(defaultForNull, "defaultForNull"); if (N.isNullOrEmpty(map)) { return defaultForNull; } final Object val = map.get(key); if (val == null) { return defaultForNull; } else if (val instanceof String) { return (String) val; } else { return N.stringOf(val); } } /** * Returns an empty {@code Optional} if the specified {@code map} is empty, or no value found by the specified {@code key}, or the value is {@code null}. * *
* Node: To follow one of general design rules in {@code Abacus}, if there is a conversion behind when the source value is not assignable to the target type, put the {@code targetType} to last parameter of the method. * Otherwise, put the {@code targetTpye} to the first parameter of the method. * * @param * @param * @param map * @param key * @param targetType * @return */ public static Optional get(final Map map, final K key, final Class targetType) { if (N.isNullOrEmpty(map)) { return Optional.empty(); } final Object val = map.get(key); if (val == null) { return Optional.empty(); } else if (targetType.isAssignableFrom(val.getClass())) { return Optional.of((T) val); } else { return Optional.of(N.convert(val, targetType)); } } /** * Returns an empty {@code Optional} if the specified {@code map} is empty, or no value found by the specified {@code key}, or the value is {@code null}. * *
* Node: To follow one of general design rules in {@code Abacus}, if there is a conversion behind when the source value is not assignable to the target type, put the {@code targetType} to last parameter of the method. * Otherwise, put the {@code targetTpye} to the first parameter of the method. * * @param * @param * @param map * @param key * @param targetType * @return */ public static Optional get(final Map map, final K key, final Type targetType) { if (N.isNullOrEmpty(map)) { return Optional.empty(); } final Object val = map.get(key); if (val == null) { return Optional.empty(); } else if (targetType.clazz().isAssignableFrom(val.getClass())) { return Optional.of((T) val); } else { return Optional.of(N.convert(val, targetType)); } } /** * Returns the mapped {@code T} or a {@code T} converted from {@code N.valueOf((Class) defaultForNull.getClass(), N.stringOf(val))}. * {@code defaultForNull} is returned if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * * @param * @param * @param map * @param key * @param defaultForNull to return if the specified {@code map} doesn't contain the specified {@code key} or the mapped value is {@code null}. * @return */ public static T get(final Map map, final K key, final T defaultForNull) { N.checkArgNotNull(defaultForNull, "defaultForNull"); if (N.isNullOrEmpty(map)) { return defaultForNull; } final Object val = map.get(key); if (val == null) { return defaultForNull; } else if (defaultForNull.getClass().isAssignableFrom(val.getClass())) { return (T) val; } else { return (T) N.convert(val, defaultForNull.getClass()); } } /** * 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 the key type * @param * @param the value type * @param map * @param key * @return */ public static > List getOrEmptyList(final Map map, final K 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 the key type * @param * @param the value type * @param map * @param key * @return */ public static > Set getOrEmptySet(final Map map, final K 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(); } } /** * 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 the key type * @param * @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 the key type * @param * @param map * @param key * @return */ public static Set getAndPutSetIfAbsent(final Map> map, final K key) { Set v = map.get(key); if (v == null) { v = N.newHashSet(); 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 the key type * @param * @param map * @param key * @return */ public static Set getAndPutLinkedHashSetIfAbsent(final Map> map, final K key) { Set v = map.get(key); if (v == null) { v = N.newLinkedHashSet(); 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 the key type * @param * @param * @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; } /** * 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 the key type * @param the value type * @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; } /** * Gets the or default for each. * * @param the key type * @param the value type * @param map * @param keys * @param defaultValue * @return */ 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 N.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; } /** * * * @param * @param * @param map * @param keys * @param defaultValue * @return */ public static List getOrDefaultIfNullForEach(final Map map, final Collection keys, final V defaultValue) { if (N.isNullOrEmpty(keys)) { return new ArrayList<>(0); } else if (N.isNullOrEmpty(map)) { return N.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) { result.add(defaultValue); } else { result.add(val); } } return result; } /** * Recursively get the values from the specified {@code map} by {@code path}. For example: *
     * 
        Map map = N.asMap("key1", "val1");
        assertEquals("val1", Maps.getByPath(map, "key1"));

        map = N.asMap("key1", N.asList("val1"));
        assertEquals("val1", Maps.getByPath(map, "key1[0]"));

        map = N.asMap("key1", N.asSet("val1"));
        assertEquals("val1", Maps.getByPath(map, "key1[0]"));

        map = N.asMap("key1", N.asList(N.asLinkedHashSet("val1", "val2")));
        assertEquals("val2", Maps.getByPath(map, "key1[0][1]"));

        map = N.asMap("key1", N.asSet(N.asList(N.asSet("val1"))));
        assertEquals("val1", Maps.getByPath(map, "key1[0][0][0]"));

        map = N.asMap("key1", N.asList(N.asLinkedHashSet("val1", N.asMap("key2", "val22"))));
        assertEquals("val22", Maps.getByPath(map, "key1[0][1].key2"));

        map = N.asMap("key1", N.asList(N.asLinkedHashSet("val1", N.asMap("key2", N.asList("val22", N.asMap("key3", "val33"))))));
        assertEquals("val33", Maps.getByPath(map, "key1[0][1].key2[1].key3"));

        map = N.asMap("key1", N.asList(N.asLinkedHashSet("val1", N.asMap("key2", N.asList("val22", N.asMap("key3", "val33"))))));
        assertNull(Maps.getByPath(map, "key1[0][2].key2[1].key3"));
     * 
     * 
* * @param * @param map * @param path * @return {@code null} if there is no value found by the specified path. */ public static T getByPath(final Map map, final String path) { final Object val = getByPathOrDefault(map, path, N.NULL_MASK); if (val == N.NULL_MASK) { return null; } return (T) val; } /** * * @param * @param map * @param path * @param targetType * @return {@code null} if there is no value found by the specified path. */ public static T getByPath(final Map map, final String path, final Class targetType) { final Object val = getByPathOrDefault(map, path, N.NULL_MASK); if (val == N.NULL_MASK) { return null; } if (val == null || targetType.isAssignableFrom(val.getClass())) { return (T) val; } else { return N.convert(val, targetType); } } /** * * @param * @param map * @param path * @param defaultValue * @return {@code defaultValue} if there is no value found by the specified path. * @see #getByPath(Map, String) */ @SuppressWarnings("rawtypes") public static T getByPathOrDefault(final Map map, final String path, final T defaultValue) { N.checkArgNotNull(defaultValue, "defaultValue"); if (N.isNullOrEmpty(map)) { return defaultValue; } final Class targetType = defaultValue == null || defaultValue == N.NULL_MASK ? null : defaultValue.getClass(); final String[] keys = Strings.split(path, '.'); Map intermediateMap = map; Collection intermediateColl = null; String key = null; for (int i = 0, len = keys.length; i < len; i++) { key = keys[i]; if (N.isNullOrEmpty(intermediateMap)) { return defaultValue; } if (key.charAt(key.length() - 1) == ']') { final int[] indexes = Strings.findAllSubstringsBetween(key, "[", "]").stream().mapToInt(Numbers::toInt).toArray(); final int idx = key.indexOf('['); intermediateColl = (Collection) intermediateMap.get(key.substring(0, idx)); for (int j = 0, idxLen = indexes.length; j < idxLen; j++) { if (N.isNullOrEmpty(intermediateColl) || intermediateColl.size() <= indexes[j]) { return defaultValue; } else { if (j == idxLen - 1) { if (i == len - 1) { final Object ret = N.getElement(intermediateColl, indexes[j]); if (ret == null || targetType == null || targetType.isAssignableFrom(ret.getClass())) { return (T) ret; } else { return (T) N.convert(ret, targetType); } } else { intermediateMap = (Map) N.getElement(intermediateColl, indexes[j]); } } else { intermediateColl = (Collection) N.getElement(intermediateColl, indexes[j]); } } } } else { if (i == len - 1) { final Object ret = intermediateMap.getOrDefault(key, defaultValue); if (ret == null || targetType == null || targetType.isAssignableFrom(ret.getClass())) { return (T) ret; } else { return (T) N.convert(ret, targetType); } } else { intermediateMap = (Map) intermediateMap.get(key); } } } return defaultValue; } /** * * @param * @param map * @param path * @return an empty {@code Nullable} if there is no value found by the specified path. */ public static Nullable getByPathIfPresent(final Map map, final String path) { final Object val = getByPathOrDefault(map, path, N.NULL_MASK); if (val == N.NULL_MASK) { return Nullable. empty(); } return Nullable.of((T) val); } /** * * @param * @param map * @param path * @param targetType * @return an empty {@code Nullable} if there is no value found by the specified path. */ public static Nullable getByPathIfPresent(final Map map, final String path, final Class targetType) { final Object val = getByPathOrDefault(map, path, N.NULL_MASK); if (val == N.NULL_MASK) { return Nullable. empty(); } if (val == null || targetType.isAssignableFrom(val.getClass())) { return Nullable.of((T) val); } else { return Nullable.of(N.convert(val, targetType)); } } /** * 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()); } /** * * @param map * @param key * @param value * @return */ 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); } /** * * @param the key type * @param the value type * @param map * @param map2 * @return */ public static Map intersection(final Map map, final Map 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())) || (val == null && entry.getValue() == null && map.containsKey(entry.getKey()))) { result.put(entry.getKey(), entry.getValue()); } } return result; } /** * * @param the key type * @param the value type * @param map * @param map2 * @return */ 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())) { result.put(entry.getKey(), Pair.of(entry.getValue(), Nullable. empty())); } else if (!N.equals(val, entry.getValue())) { result.put(entry.getKey(), Pair.of(entry.getValue(), Nullable.of(val))); } } } return result; } /** * * @param the key type * @param the value type * @param map * @param map2 * @return */ 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<>() : new LinkedHashMap<>(); 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)) { result.put(key, Pair.of(Nullable.of(entry.getValue()), Nullable. empty())); } else if (!N.equals(val2, entry.getValue())) { 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())) { result.put(entry.getKey(), Pair.of(Nullable. empty(), Nullable.of(entry.getValue()))); } } } } return result; } /** * Put if absent. * * @param the key type * @param the value type * @param map * @param key * @param value * @return */ 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; } /** * Put if absent. * * @param the key type * @param the value type * @param map * @param key * @param supplier * @return */ 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 the key type * @param the value type * @param map * @param entry * @return */ public static boolean remove(final Map map, Map.Entry entry) { return remove(map, entry.getKey(), entry.getValue()); } /** * * @param the key type * @param the value type * @param map * @param key * @param value * @return */ 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; } /** * Removes the keys. * * @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 the key type * @param the value type * @param * @param map * @param filter * @return {@code true} if there are one or more than one entries removed from the specified map. * @throws E the e */ public static boolean removeIf(final Map map, final Throwables.Predicate, 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 the key type * @param the value type * @param * @param map * @param filter * @return {@code true} if there are one or more than one entries removed from the specified map. * @throws E the e */ public static boolean removeIfKey(final Map map, final Throwables.Predicate 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 the key type * @param the value type * @param * @param map * @param filter * @return {@code true} if there are one or more than one entries removed from the specified map. * @throws E the e */ public static boolean removeIfValue(final Map map, final Throwables.Predicate 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; } /** * * @param the key type * @param the value type * @param map * @param key * @param oldValue * @param newValue * @return */ 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; } /** * * @param the key type * @param the value type * @param map * @param key * @param newValue * @return */ 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; } /** * * @param the key type * @param the value type * @param * @param map * @param function * @throws E the e */ public static void replaceAll(final Map map, final Throwables.BiFunction 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); } } } // Replaced with N.forEach(Map....) // public static void forEach(final Map map, final Throwables.Consumer, E> action) throws E { // N.checkArgNotNull(action); // // if (N.isNullOrEmpty(map)) { // return; // } // // for (Map.Entry entry : map.entrySet()) { // action.accept(entry); // } // } // // /** // * // * @param the key type // * @param the value type // * @param // * @param map // * @param action // * @throws E the e // */ // public static void forEach(final Map map, final Throwables.BiConsumer action) throws E { // N.checkArgNotNull(action); // // if (N.isNullOrEmpty(map)) { // return; // } // // for (Map.Entry entry : map.entrySet()) { // action.accept(entry.getKey(), entry.getValue()); // } // } /** * * @param the key type * @param the value type * @param * @param map * @param predicate * @return * @throws E the e */ public static Map filter(final Map map, final Throwables.BiPredicate 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; } /** * Filter by key. * * @param the key type * @param the value type * @param * @param map * @param predicate * @return * @throws E the e */ public static Map filterByKey(final Map map, final Throwables.Predicate 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; } /** * Filter by value. * * @param the key type * @param the value type * @param * @param map * @param predicate * @return * @throws E the e */ public static Map filterByValue(final Map map, final Throwables.Predicate 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 the key type * @param the value type * @param map * @return * @see Multimap#invertFrom(Map, 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 the key type * @param the value type * @param map * @param mergeOp * @return */ public static Map invert(final Map map, final BinaryOperator mergeOp) { N.checkArgNotNull(mergeOp, "mergeOp"); if (map == null) { return new HashMap<>(); } final Map result = newOrderingMap(map); K oldVal = null; for (Map.Entry entry : map.entrySet()) { oldVal = result.get(entry.getValue()); if (oldVal != null || result.containsKey(entry.getValue())) { result.put(entry.getValue(), mergeOp.apply(oldVal, entry.getKey())); } else { result.put(entry.getValue(), entry.getKey()); } } return result; } /** * * @param the key type * @param the value type * @param map * @return * @see Multimap#flatInvertFrom(Map, 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 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; } /** * {a=[1, 2, 3], b=[4, 5, 6], c=[7, 8]} -> [{a=1, b=4, c=7}, {a=2, b=5, c=8}, {a=3, b=6}]. * * @param * @param * @param map * @return */ public static List> flatToMap(final Map> map) { if (map == null) { return new ArrayList<>(); } int maxValueSize = 0; for (Collection v : map.values()) { maxValueSize = N.max(maxValueSize, N.size(v)); } final List> result = new ArrayList<>(maxValueSize); for (int i = 0; i < maxValueSize; i++) { result.add(newOrderingMap(map)); } K key = null; Iterator iter = null; for (Map.Entry> entry : map.entrySet()) { if (N.isNullOrEmpty(entry.getValue())) { continue; } key = entry.getKey(); iter = entry.getValue().iterator(); for (int i = 0; iter.hasNext(); i++) { result.get(i).put(key, iter.next()); } } return result; } /** * * @param map * @return */ public static Map flatten(Map map) { return flatten(map, Suppliers. ofMap()); } /** * * @param * @param map * @param mapSupplier * @return */ public static > M flatten(Map map, Supplier mapSupplier) { return flatten(map, ".", mapSupplier); } /** * * @param * @param map * @param delimiter * @param mapSupplier * @return */ public static > M flatten(Map map, String delimiter, Supplier mapSupplier) { final M result = mapSupplier.get(); flatten(map, null, delimiter, result); return result; } /** * * @param map * @param prefix * @param delimiter * @param output */ private static void flatten(Map map, String prefix, String delimiter, Map output) { if (N.isNullOrEmpty(map)) { return; } if (N.isNullOrEmpty(prefix)) { for (Map.Entry entry : map.entrySet()) { if (entry.getValue() instanceof Map) { flatten((Map) entry.getValue(), entry.getKey(), delimiter, output); } else { output.put(entry.getKey(), entry.getValue()); } } } else { for (Map.Entry entry : map.entrySet()) { if (entry.getValue() instanceof Map) { flatten((Map) entry.getValue(), prefix + delimiter + entry.getKey(), delimiter, output); } else { output.put(prefix + delimiter + entry.getKey(), entry.getValue()); } } } } /** * * @param map * @return */ public static Map unflatten(Map map) { return unflatten(map, Suppliers. ofMap()); } /** * * @param * @param map * @param mapSupplier * @return */ public static > M unflatten(Map map, Supplier mapSupplier) { return unflatten(map, ".", mapSupplier); } /** * * @param * @param map * @param delimiter * @param mapSupplier * @return */ public static > M unflatten(Map map, String delimiter, Supplier mapSupplier) { final M result = mapSupplier.get(); final Splitter keySplitter = Splitter.with(delimiter); if (N.notNullOrEmpty(map)) { for (Map.Entry entry : map.entrySet()) { if (entry.getKey().indexOf(delimiter) >= 0) { final String[] keys = keySplitter.splitToArray(entry.getKey()); Map lastMap = result; for (int i = 0, to = keys.length - 1; i < to; i++) { Map tmp = (Map) lastMap.get(keys[i]); if (tmp == null) { tmp = mapSupplier.get(); lastMap.put(keys[i], tmp); } lastMap = tmp; } lastMap.put(keys[keys.length - 1], entry.getValue()); } else { result.put(entry.getKey(), entry.getValue()); } } } return result; } // /** // * Map type 2 supplier. // * // * @param mapType // * @return // */ // @SuppressWarnings("rawtypes") // static Supplier mapType2Supplier(final Class mapType) { // return Suppliers.ofMap(mapType); // } /** * * @param the key type * @param the value type * @param map * @param function */ static void replaceAll(Map map, BiFunction function) { N.checkArgNotNull(function); try { for (Map.Entry entry : map.entrySet()) { entry.setValue(function.apply(entry.getKey(), entry.getValue())); } } catch (IllegalStateException ise) { throw new ConcurrentModificationException(ise); } } /** * * @param the key type * @param the value type * @param map * @param key * @param value * @param remappingFunction */ public static void merge(Map map, K key, V value, BinaryOperator remappingFunction) { final V oldValue = map.get(key); if (oldValue == null && !map.containsKey(key)) { map.put(key, value); } else { map.put(key, remappingFunction.apply(oldValue, value)); } } /** * Map to bean. * * @param * @param m * @param targetClass * @return */ public static T map2Bean(final Map m, final Class targetClass) { return map2Bean(m, false, true, targetClass); } /** * Map to bean. * * @param * @param m * @param ignoreNullProperty * @param ignoreUnmatchedProperty * @param targetClass * @return */ @SuppressWarnings("unchecked") public static T map2Bean(final Map m, final boolean ignoreNullProperty, final boolean ignoreUnmatchedProperty, final Class targetClass) { checkBeanClass(targetClass); if (m == null) { return null; } final BeanInfo beanInfo = ParserUtil.getBeanInfo(targetClass); final Object result = beanInfo.createBeanResult(); PropInfo propInfo = null; String propName = null; Object propValue = null; for (Map.Entry entry : m.entrySet()) { propName = entry.getKey(); propValue = entry.getValue(); if (ignoreNullProperty && (propValue == null)) { continue; } propInfo = beanInfo.getPropInfo(propName); if (propInfo == null) { beanInfo.setPropValue(result, propName, propValue, ignoreUnmatchedProperty); } else { if (propValue != null && N.typeOf(propValue.getClass()).isMap() && propInfo.type.isBean()) { propInfo.setPropValue(result, map2Bean((Map) propValue, ignoreNullProperty, ignoreUnmatchedProperty, propInfo.clazz)); } else { propInfo.setPropValue(result, propValue); } } } return beanInfo.finishBeanResult(result); } /** * Map to bean. * * @param * @param m * @param selectPropNames * @param targetClass * @return */ public static T map2Bean(final Map m, final Collection selectPropNames, final Class targetClass) { checkBeanClass(targetClass); if (m == null) { return null; } final BeanInfo beanInfo = ParserUtil.getBeanInfo(targetClass); final Object result = beanInfo.createBeanResult(); PropInfo propInfo = null; Object propValue = null; for (String propName : selectPropNames) { propValue = m.get(propName); if (propValue == null && !m.containsKey(propName)) { throw new IllegalArgumentException("Property name: " + propName + " is not found in map with key set: " + m.keySet()); } propInfo = beanInfo.getPropInfo(propName); if (propInfo == null) { beanInfo.setPropValue(result, propName, propValue, false); } else { if (propValue != null && N.typeOf(propValue.getClass()).isMap() && propInfo.type.isBean()) { propInfo.setPropValue(result, map2Bean((Map) propValue, propInfo.clazz)); } else { propInfo.setPropValue(result, propValue); } } } return beanInfo.finishBeanResult(result); } /** * Map to bean. * * @param * @param mList * @param targetClass * @return */ public static List map2Bean(final Collection> mList, final Class targetClass) { return map2Bean(mList, false, true, targetClass); } /** * Map to bean. * * @param * @param mList * @param igoreNullProperty * @param ignoreUnmatchedProperty * @param targetClass * @return */ public static List map2Bean(final Collection> mList, final boolean igoreNullProperty, final boolean ignoreUnmatchedProperty, final Class targetClass) { checkBeanClass(targetClass); final List beanList = new ArrayList<>(mList.size()); for (Map m : mList) { beanList.add(map2Bean(m, igoreNullProperty, ignoreUnmatchedProperty, targetClass)); } return beanList; } /** * Map to bean. * * @param * @param mList * @param selectPropNames * @param targetClass * @return */ public static List map2Bean(final Collection> mList, final Collection selectPropNames, final Class targetClass) { checkBeanClass(targetClass); final List beanList = new ArrayList<>(mList.size()); for (Map m : mList) { beanList.add(map2Bean(m, selectPropNames, targetClass)); } return beanList; } /** * Bean to map. * * @param bean * @return */ public static Map bean2Map(final Object bean) { return bean2Map(bean, IntFunctions.ofLinkedHashMap()); } /** * Bean to map. * * @param * @param bean * @param mapSupplier * @return */ public static > M bean2Map(final Object bean, final IntFunction mapSupplier) { return bean2Map(bean, null, mapSupplier); } /** * Bean to map. * * @param bean * @param selectPropNames * @return */ public static Map bean2Map(final Object bean, final Collection selectPropNames) { return bean2Map(bean, selectPropNames, IntFunctions.ofLinkedHashMap()); } /** * Bean to map. * * @param * @param bean * @param selectPropNames * @param mapSupplier * @return */ public static > M bean2Map(final Object bean, final Collection selectPropNames, final IntFunction mapSupplier) { return bean2Map(bean, selectPropNames, NamingPolicy.LOWER_CAMEL_CASE, mapSupplier); } /** * Bean to map. * * @param * @param bean * @param selectPropNames * @param keyNamingPolicy * @param mapSupplier * @return */ public static > M bean2Map(final Object bean, final Collection selectPropNames, final NamingPolicy keyNamingPolicy, final IntFunction mapSupplier) { final M resultMap = mapSupplier.apply(N.isNullOrEmpty(selectPropNames) ? ClassUtil.getPropNameList(bean.getClass()).size() : selectPropNames.size()); bean2Map(resultMap, bean, selectPropNames, keyNamingPolicy); return resultMap; } /** * Bean to map. * * @param * @param resultMap * @param bean * @return */ public static > M bean2Map(final M resultMap, final Object bean) { return bean2Map(resultMap, bean, null); } /** * Bean to map. * * @param * @param resultMap * @param bean * @param selectPropNames * @return */ public static > M bean2Map(final M resultMap, final Object bean, final Collection selectPropNames) { return bean2Map(resultMap, bean, selectPropNames, NamingPolicy.LOWER_CAMEL_CASE); } /** * Bean to map. * * @param * @param resultMap * @param bean * @param selectPropNames * @param keyNamingPolicy * @return */ public static > M bean2Map(final M resultMap, final Object bean, final Collection selectPropNames, NamingPolicy keyNamingPolicy) { keyNamingPolicy = keyNamingPolicy == null ? NamingPolicy.LOWER_CAMEL_CASE : keyNamingPolicy; final boolean isLowerCamelCaseOrNoChange = NamingPolicy.LOWER_CAMEL_CASE.equals(keyNamingPolicy) || NamingPolicy.NO_CHANGE.equals(keyNamingPolicy); final Class beanClass = bean.getClass(); final BeanInfo beanInfo = ParserUtil.getBeanInfo(beanClass); if (N.isNullOrEmpty(selectPropNames)) { bean2Map(resultMap, bean, true, null, keyNamingPolicy); } else { PropInfo propInfo = null; Object propValue = null; for (String propName : selectPropNames) { propInfo = beanInfo.getPropInfo(propName); if (propInfo == null) { throw new IllegalArgumentException("Property: " + propName + " is not found in bean class: " + beanClass); //NOSONAR } propValue = propInfo.getPropValue(bean); if (isLowerCamelCaseOrNoChange) { resultMap.put(propName, propValue); } else { resultMap.put(keyNamingPolicy.convert(propName), propValue); } } } return resultMap; } /** * Bean to map. * * @param bean * @param ignoreNullProperty * @return */ public static Map bean2Map(final Object bean, final boolean ignoreNullProperty) { return bean2Map(bean, ignoreNullProperty, null); } /** * Bean to map. * * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @return */ public static Map bean2Map(final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames) { return bean2Map(bean, ignoreNullProperty, ignoredPropNames, NamingPolicy.LOWER_CAMEL_CASE); } /** * Bean to map. * * @param * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @param mapSupplier * @return */ public static > M bean2Map(final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames, final IntFunction mapSupplier) { return bean2Map(bean, ignoreNullProperty, ignoredPropNames, NamingPolicy.LOWER_CAMEL_CASE, mapSupplier); } /** * Bean to map. * * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @param keyNamingPolicy * @return */ public static Map bean2Map(final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames, final NamingPolicy keyNamingPolicy) { return bean2Map(bean, ignoreNullProperty, ignoredPropNames, keyNamingPolicy, IntFunctions.ofLinkedHashMap()); } /** * Bean to map. * * @param * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @param keyNamingPolicy * @param mapSupplier * @return */ public static > M bean2Map(final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames, final NamingPolicy keyNamingPolicy, final IntFunction mapSupplier) { if (bean == null) { return mapSupplier.apply(0); } final int beanPropNameSize = ClassUtil.getPropNameList(bean.getClass()).size(); final int initCapacity = beanPropNameSize - N.size(ignoredPropNames); final M resultMap = mapSupplier.apply(initCapacity); bean2Map(resultMap, bean, ignoreNullProperty, ignoredPropNames, keyNamingPolicy); return resultMap; } /** * Bean to map. * * @param * @param resultMap * @param bean * @param ignoreNullProperty * @return */ public static > M bean2Map(final M resultMap, final Object bean, final boolean ignoreNullProperty) { return bean2Map(resultMap, bean, ignoreNullProperty, null); } /** * Bean to map. * * @param * @param resultMap * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @return */ public static > M bean2Map(final M resultMap, final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames) { return bean2Map(resultMap, bean, ignoreNullProperty, ignoredPropNames, NamingPolicy.LOWER_CAMEL_CASE); } /** * Bean to map. * * @param * @param resultMap * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @param keyNamingPolicy * @return */ public static > M bean2Map(final M resultMap, final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames, NamingPolicy keyNamingPolicy) { keyNamingPolicy = keyNamingPolicy == null ? NamingPolicy.LOWER_CAMEL_CASE : keyNamingPolicy; final boolean isLowerCamelCaseOrNoChange = NamingPolicy.LOWER_CAMEL_CASE.equals(keyNamingPolicy) || NamingPolicy.NO_CHANGE.equals(keyNamingPolicy); final boolean hasIgnoredPropNames = N.notNullOrEmpty(ignoredPropNames); final Class beanClass = bean.getClass(); final BeanInfo beanInfo = ParserUtil.getBeanInfo(beanClass); String propName = null; Object propValue = null; for (PropInfo propInfo : beanInfo.propInfoList) { propName = propInfo.name; if (hasIgnoredPropNames && ignoredPropNames.contains(propName)) { continue; } propValue = propInfo.getPropValue(bean); if (ignoreNullProperty && (propValue == null)) { continue; } if (isLowerCamelCaseOrNoChange) { resultMap.put(propName, propValue); } else { resultMap.put(keyNamingPolicy.convert(propName), propValue); } } return resultMap; } /** * Bean to map. * * @param bean * @return */ public static Map deepBean2Map(final Object bean) { return deepBean2Map(bean, IntFunctions.ofLinkedHashMap()); } /** * Bean to map. * * @param * @param bean * @param mapSupplier * @return */ public static > M deepBean2Map(final Object bean, final IntFunction mapSupplier) { return deepBean2Map(bean, null, mapSupplier); } /** * Bean to map. * * @param bean * @param selectPropNames * @return */ public static Map deepBean2Map(final Object bean, final Collection selectPropNames) { return deepBean2Map(bean, selectPropNames, IntFunctions.ofLinkedHashMap()); } /** * Bean to map. * * @param * @param bean * @param selectPropNames * @param mapSupplier * @return */ public static > M deepBean2Map(final Object bean, final Collection selectPropNames, final IntFunction mapSupplier) { return deepBean2Map(bean, selectPropNames, NamingPolicy.LOWER_CAMEL_CASE, mapSupplier); } /** * Bean to map. * * @param * @param bean * @param selectPropNames * @param keyNamingPolicy * @param mapSupplier * @return */ public static > M deepBean2Map(final Object bean, final Collection selectPropNames, final NamingPolicy keyNamingPolicy, final IntFunction mapSupplier) { final M resultMap = mapSupplier.apply(N.isNullOrEmpty(selectPropNames) ? ClassUtil.getPropNameList(bean.getClass()).size() : selectPropNames.size()); deepBean2Map(resultMap, bean, selectPropNames, keyNamingPolicy); return resultMap; } /** * Bean to map. * * @param * @param resultMap * @param bean * @return */ public static > M deepBean2Map(final M resultMap, final Object bean) { return deepBean2Map(resultMap, bean, null); } /** * Bean to map. * * @param * @param resultMap * @param bean * @param selectPropNames * @return */ public static > M deepBean2Map(final M resultMap, final Object bean, final Collection selectPropNames) { return deepBean2Map(resultMap, bean, selectPropNames, NamingPolicy.LOWER_CAMEL_CASE); } /** * Bean to map. * * @param * @param resultMap * @param bean * @param selectPropNames * @param keyNamingPolicy * @return */ public static > M deepBean2Map(final M resultMap, final Object bean, final Collection selectPropNames, final NamingPolicy keyNamingPolicy) { final boolean isLowerCamelCaseOrNoChange = keyNamingPolicy == null || NamingPolicy.LOWER_CAMEL_CASE.equals(keyNamingPolicy) || NamingPolicy.NO_CHANGE.equals(keyNamingPolicy); final Class beanClass = bean.getClass(); final BeanInfo beanInfo = ParserUtil.getBeanInfo(beanClass); if (N.isNullOrEmpty(selectPropNames)) { deepBean2Map(resultMap, bean, true, null, keyNamingPolicy); } else { PropInfo propInfo = null; Object propValue = null; for (String propName : selectPropNames) { propInfo = beanInfo.getPropInfo(propName); if (propInfo == null) { throw new IllegalArgumentException("Property: " + propName + " is not found in bean class: " + beanClass); } propValue = propInfo.getPropValue(bean); if ((propValue == null) || !propInfo.jsonXmlType.isBean()) { if (isLowerCamelCaseOrNoChange) { resultMap.put(propName, propValue); } else { resultMap.put(keyNamingPolicy.convert(propName), propValue); } } else { if (isLowerCamelCaseOrNoChange) { resultMap.put(propName, deepBean2Map(propValue, true, null, keyNamingPolicy)); } else { resultMap.put(keyNamingPolicy.convert(propName), deepBean2Map(propValue, true, null, keyNamingPolicy)); } } } } return resultMap; } /** * Bean to map. * * @param bean * @param ignoreNullProperty * @return */ public static Map deepBean2Map(final Object bean, final boolean ignoreNullProperty) { return deepBean2Map(bean, ignoreNullProperty, null); } /** * Bean to map. * * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @return */ public static Map deepBean2Map(final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames) { return deepBean2Map(bean, ignoreNullProperty, ignoredPropNames, NamingPolicy.LOWER_CAMEL_CASE); } /** * Bean to map. * * @param * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @param mapSupplier * @return */ public static > M deepBean2Map(final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames, final IntFunction mapSupplier) { return deepBean2Map(bean, ignoreNullProperty, ignoredPropNames, NamingPolicy.LOWER_CAMEL_CASE, mapSupplier); } /** * Bean to map. * * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @param keyNamingPolicy * @return */ public static Map deepBean2Map(final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames, final NamingPolicy keyNamingPolicy) { return deepBean2Map(bean, ignoreNullProperty, ignoredPropNames, keyNamingPolicy, IntFunctions.ofLinkedHashMap()); } /** * Bean to map. * * @param * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @param keyNamingPolicy * @param mapSupplier * @return */ public static > M deepBean2Map(final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames, final NamingPolicy keyNamingPolicy, final IntFunction mapSupplier) { if (bean == null) { return mapSupplier.apply(0); } final int beanPropNameSize = ClassUtil.getPropNameList(bean.getClass()).size(); final int initCapacity = beanPropNameSize - N.size(ignoredPropNames); final M resultMap = mapSupplier.apply(initCapacity); deepBean2Map(resultMap, bean, ignoreNullProperty, ignoredPropNames, keyNamingPolicy); return resultMap; } /** * Bean to map. * * @param * @param resultMap * @param bean * @param ignoreNullProperty * @return */ public static > M deepBean2Map(final M resultMap, final Object bean, final boolean ignoreNullProperty) { return deepBean2Map(resultMap, bean, ignoreNullProperty, null); } /** * Bean to map. * * @param * @param resultMap * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @return */ public static > M deepBean2Map(final M resultMap, final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames) { return deepBean2Map(resultMap, bean, ignoreNullProperty, ignoredPropNames, NamingPolicy.LOWER_CAMEL_CASE); } /** * Bean to map. * * @param * @param resultMap * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @param keyNamingPolicy * @return */ public static > M deepBean2Map(final M resultMap, final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames, final NamingPolicy keyNamingPolicy) { final boolean isLowerCamelCaseOrNoChange = keyNamingPolicy == null || NamingPolicy.LOWER_CAMEL_CASE.equals(keyNamingPolicy) || NamingPolicy.NO_CHANGE.equals(keyNamingPolicy); final boolean hasIgnoredPropNames = N.notNullOrEmpty(ignoredPropNames); final Class beanClass = bean.getClass(); final BeanInfo beanInfo = ParserUtil.getBeanInfo(beanClass); String propName = null; Object propValue = null; for (PropInfo propInfo : beanInfo.propInfoList) { propName = propInfo.name; if (hasIgnoredPropNames && ignoredPropNames.contains(propName)) { continue; } propValue = propInfo.getPropValue(bean); if (ignoreNullProperty && (propValue == null)) { continue; } if ((propValue == null) || !propInfo.jsonXmlType.isBean()) { if (isLowerCamelCaseOrNoChange) { resultMap.put(propName, propValue); } else { resultMap.put(keyNamingPolicy.convert(propName), propValue); } } else { if (isLowerCamelCaseOrNoChange) { resultMap.put(propName, deepBean2Map(propValue, ignoreNullProperty, null, keyNamingPolicy)); } else { resultMap.put(keyNamingPolicy.convert(propName), deepBean2Map(propValue, ignoreNullProperty, null, keyNamingPolicy)); } } } return resultMap; } /** * Bean to map. * * @param bean * @return */ public static Map bean2FlatMap(final Object bean) { return bean2FlatMap(bean, IntFunctions.ofLinkedHashMap()); } /** * Bean to map. * * @param * @param bean * @param mapSupplier * @return */ public static > M bean2FlatMap(final Object bean, final IntFunction mapSupplier) { return bean2FlatMap(bean, null, mapSupplier); } /** * Bean to map. * * @param bean * @param selectPropNames * @return */ public static Map bean2FlatMap(final Object bean, final Collection selectPropNames) { return bean2FlatMap(bean, selectPropNames, IntFunctions.ofLinkedHashMap()); } /** * Bean to map. * * @param * @param bean * @param selectPropNames * @param mapSupplier * @return */ public static > M bean2FlatMap(final Object bean, final Collection selectPropNames, final IntFunction mapSupplier) { return bean2FlatMap(bean, selectPropNames, NamingPolicy.LOWER_CAMEL_CASE, mapSupplier); } /** * Bean to map. * * @param * @param bean * @param selectPropNames * @param keyNamingPolicy * @param mapSupplier * @return */ public static > M bean2FlatMap(final Object bean, final Collection selectPropNames, final NamingPolicy keyNamingPolicy, final IntFunction mapSupplier) { final M resultMap = mapSupplier.apply(N.isNullOrEmpty(selectPropNames) ? ClassUtil.getPropNameList(bean.getClass()).size() : selectPropNames.size()); bean2FlatMap(resultMap, bean, selectPropNames, keyNamingPolicy); return resultMap; } /** * Bean to map. * * @param * @param resultMap * @param bean * @return */ public static > M bean2FlatMap(final M resultMap, final Object bean) { return bean2FlatMap(resultMap, bean, null); } /** * Bean to map. * * @param * @param resultMap * @param bean * @param selectPropNames * @return */ public static > M bean2FlatMap(final M resultMap, final Object bean, final Collection selectPropNames) { return bean2FlatMap(resultMap, bean, selectPropNames, NamingPolicy.LOWER_CAMEL_CASE); } /** * Bean to map. * * @param * @param resultMap * @param bean * @param selectPropNames * @param keyNamingPolicy * @return */ public static > M bean2FlatMap(final M resultMap, final Object bean, final Collection selectPropNames, NamingPolicy keyNamingPolicy) { keyNamingPolicy = keyNamingPolicy == null ? NamingPolicy.LOWER_CAMEL_CASE : keyNamingPolicy; final boolean isLowerCamelCaseOrNoChange = NamingPolicy.LOWER_CAMEL_CASE.equals(keyNamingPolicy) || NamingPolicy.NO_CHANGE.equals(keyNamingPolicy); final Class beanClass = bean.getClass(); final BeanInfo beanInfo = ParserUtil.getBeanInfo(beanClass); if (N.isNullOrEmpty(selectPropNames)) { bean2FlatMap(resultMap, bean, true, null, keyNamingPolicy); } else { PropInfo propInfo = null; Object propValue = null; for (String propName : selectPropNames) { propInfo = beanInfo.getPropInfo(propName); if (propInfo == null) { throw new IllegalArgumentException("Property: " + propName + " is not found in bean class: " + beanClass); } propValue = propInfo.getPropValue(bean); if ((propValue == null) || !propInfo.jsonXmlType.isBean()) { if (isLowerCamelCaseOrNoChange) { resultMap.put(propName, propValue); } else { resultMap.put(keyNamingPolicy.convert(propName), propValue); } } else { bean2FlatMap(resultMap, propValue, true, null, keyNamingPolicy, isLowerCamelCaseOrNoChange ? propName : keyNamingPolicy.convert(propName)); } } } return resultMap; } /** * Bean to map. * * @param bean * @param ignoreNullProperty * @return */ public static Map bean2FlatMap(final Object bean, final boolean ignoreNullProperty) { return bean2FlatMap(bean, ignoreNullProperty, null); } /** * Bean to map. * * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @return */ public static Map bean2FlatMap(final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames) { return bean2FlatMap(bean, ignoreNullProperty, ignoredPropNames, NamingPolicy.LOWER_CAMEL_CASE); } /** * Bean to map. * * @param * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @param mapSupplier * @return */ public static > M bean2FlatMap(final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames, final IntFunction mapSupplier) { return bean2FlatMap(bean, ignoreNullProperty, ignoredPropNames, NamingPolicy.LOWER_CAMEL_CASE, mapSupplier); } /** * Bean to map. * * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @param keyNamingPolicy * @return */ public static Map bean2FlatMap(final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames, final NamingPolicy keyNamingPolicy) { return bean2FlatMap(bean, ignoreNullProperty, ignoredPropNames, keyNamingPolicy, IntFunctions.ofLinkedHashMap()); } /** * Bean to map. * * @param * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @param keyNamingPolicy * @param mapSupplier * @return */ public static > M bean2FlatMap(final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames, final NamingPolicy keyNamingPolicy, final IntFunction mapSupplier) { if (bean == null) { return mapSupplier.apply(0); } final int beanPropNameSize = ClassUtil.getPropNameList(bean.getClass()).size(); final int initCapacity = beanPropNameSize - N.size(ignoredPropNames); final M resultMap = mapSupplier.apply(initCapacity); bean2FlatMap(resultMap, bean, ignoreNullProperty, ignoredPropNames, keyNamingPolicy); return resultMap; } /** * Bean to map. * * @param * @param resultMap * @param bean * @param ignoreNullProperty * @return */ public static > M bean2FlatMap(final M resultMap, final Object bean, final boolean ignoreNullProperty) { return bean2FlatMap(resultMap, bean, ignoreNullProperty, null); } /** * Bean to map. * * @param * @param resultMap * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @return */ public static > M bean2FlatMap(final M resultMap, final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames) { return bean2FlatMap(resultMap, bean, ignoreNullProperty, ignoredPropNames, NamingPolicy.LOWER_CAMEL_CASE); } /** * Bean to map. * * @param * @param resultMap * @param bean * @param ignoreNullProperty * @param ignoredPropNames * @param keyNamingPolicy * @return */ public static > M bean2FlatMap(final M resultMap, final Object bean, final boolean ignoreNullProperty, final Set ignoredPropNames, final NamingPolicy keyNamingPolicy) { return bean2FlatMap(resultMap, bean, ignoreNullProperty, ignoredPropNames, keyNamingPolicy, null); } static > T bean2FlatMap(final T resultMap, final Object bean, final boolean ignoreNullProperty, final Collection ignoredPropNames, final NamingPolicy keyNamingPolicy, final String parentPropName) { final boolean isLowerCamelCaseOrNoChange = keyNamingPolicy == null || NamingPolicy.LOWER_CAMEL_CASE.equals(keyNamingPolicy) || NamingPolicy.NO_CHANGE.equals(keyNamingPolicy); final boolean hasIgnoredPropNames = N.notNullOrEmpty(ignoredPropNames); final boolean isNullParentPropName = (parentPropName == null); final Class beanClass = bean.getClass(); String propName = null; Object propValue = null; for (PropInfo propInfo : ParserUtil.getBeanInfo(beanClass).propInfoList) { propName = propInfo.name; if (hasIgnoredPropNames && ignoredPropNames.contains(propName)) { continue; } propValue = propInfo.getPropValue(bean); if (ignoreNullProperty && (propValue == null)) { continue; } if ((propValue == null) || !propInfo.jsonXmlType.isBean()) { if (isNullParentPropName) { if (isLowerCamelCaseOrNoChange) { resultMap.put(propName, propValue); } else { resultMap.put(keyNamingPolicy.convert(propName), propValue); } } else { if (isLowerCamelCaseOrNoChange) { resultMap.put(parentPropName + WD.PERIOD + propName, propValue); } else { resultMap.put(parentPropName + WD.PERIOD + keyNamingPolicy.convert(propName), propValue); } } } else { if (isNullParentPropName) { bean2FlatMap(resultMap, propValue, ignoreNullProperty, null, keyNamingPolicy, isLowerCamelCaseOrNoChange ? propName : keyNamingPolicy.convert(propName)); } else { bean2FlatMap(resultMap, propValue, ignoreNullProperty, null, keyNamingPolicy, parentPropName + WD.PERIOD + (isLowerCamelCaseOrNoChange ? propName : keyNamingPolicy.convert(propName))); } } } return resultMap; } /** * Check bean class. * * @param * @param cls */ private static void checkBeanClass(final Class cls) { if (!ClassUtil.isBeanClass(cls)) { throw new IllegalArgumentException("No property getter/setter method is found in the specified class: " + ClassUtil.getCanonicalClassName(cls)); } } // @SuppressWarnings("deprecation") // @Beta // public static Map record2Map(final T record) { // if (record == null) { // return null; // } // // final Class recordClass = record.getClass(); // // return record2Map(new LinkedHashMap<>(ClassUtil.getRecordInfo(recordClass).fieldNames().size()), record); // } // // @Beta // public static > M record2Map(final T record, final Supplier mapSupplier) { // if (record == null) { // return null; // } // // return record2Map(mapSupplier.get(), record); // } // // @SuppressWarnings("deprecation") // @Beta // public static > M record2Map(final T record, final IntFunction mapSupplier) { // if (record == null) { // return null; // } // // final Class recordClass = record.getClass(); // // return record2Map(mapSupplier.apply(ClassUtil.getRecordInfo(recordClass).fieldNames().size()), record); // } // // @Beta // static > M record2Map(final M resultMap, final Object record) { // if (record == null) { // return resultMap; // } // // final Class recordClass = record.getClass(); // // @SuppressWarnings("deprecation") // final RecordInfo recordInfo = ClassUtil.getRecordInfo(recordClass); // // try { // for (Tuple5, Integer> tp : recordInfo.fieldMap().values()) { // resultMap.put(tp._1, tp._3.invoke(record)); // } // } catch (IllegalAccessException | InvocationTargetException e) { // // Should never happen. // throw ExceptionUtil.toRuntimeException(e); // } // // return resultMap; // } // // @Beta // public static T map2Record(final Map map, final Class recordClass) { // @SuppressWarnings("deprecation") // final RecordInfo recordInfo = ClassUtil.getRecordInfo(recordClass); // // if (map == null) { // return null; // } // // final Object[] args = new Object[recordInfo.fieldNames().size()]; // Object val = null; // int idx = 0; // // for (String fieldName : recordInfo.fieldNames()) { // val = map.get(fieldName); // // // TODO, should be ignored? // // if (val == null && !map.containsKey(tp._1)) { // // throw new IllegalArgumentException("No value found for field: " + tp._1 + " from the input map"); // // } // // args[idx++] = val; // } // // return (T) recordInfo.creator().apply(args); // } public static class MapGetter { private final Map map; private final boolean defaultForPrimitive; MapGetter(final Map map, final boolean defaultForPrimitive) { this.map = map; this.defaultForPrimitive = defaultForPrimitive; } /** * * * @param * @param * @param map * @return */ public static MapGetter of(final Map map) { return of(map, false); } /** * * * @param * @param * @param map * @param defaultForPrimitive * @return */ public static MapGetter of(final Map map, final boolean defaultForPrimitive) { return new MapGetter<>(map, defaultForPrimitive); } /** * * * @param key * @return */ public Boolean getBoolean(Object key) { Object value = map.get(key); if (value == null && defaultForPrimitive) { return Boolean.FALSE; } else if (value instanceof Boolean) { return (Boolean) value; } return N.parseBoolean(N.toString(value)); } /** * * * @param key * @return */ public Character getChar(Object key) { Object value = map.get(key); if (value == null && defaultForPrimitive) { return 0; } else if (value instanceof Character) { return (Character) value; } return N.parseChar(N.toString(value)); } /** * * * @param key * @return */ public Byte getByte(Object key) { Object value = map.get(key); if (value == null && defaultForPrimitive) { return 0; } else if (value instanceof Byte) { return (Byte) value; } return Numbers.toByte(value); } /** * * * @param key * @return */ public Short getShort(Object key) { Object value = map.get(key); if (value == null && defaultForPrimitive) { return 0; } else if (value instanceof Short) { return (Short) value; } return Numbers.toShort(value); } /** * * * @param key * @return */ public Integer getInt(Object key) { Object value = map.get(key); if (value == null && defaultForPrimitive) { return 0; } else if (value instanceof Integer) { return (Integer) value; } return Numbers.toInt(value); } /** * * * @param key * @return */ public Long getLong(Object key) { Object value = map.get(key); if (value == null && defaultForPrimitive) { return 0L; } else if (value instanceof Long) { return (Long) value; } return Numbers.toLong(value); } /** * * * @param key * @return */ public Float getFloat(Object key) { Object value = map.get(key); if (value == null && defaultForPrimitive) { return 0F; } else if (value instanceof Float) { return (Float) value; } return Numbers.toFloat(value); } /** * * * @param key * @return */ public Double getDouble(Object key) { Object value = map.get(key); if (value == null && defaultForPrimitive) { return 0d; } else if (value instanceof Double) { return (Double) value; } return Numbers.toDouble(value); } /** * * * @param key * @return */ public BigInteger getBigInteger(Object key) { Object value = map.get(key); if (value == null || value instanceof BigInteger) { return (BigInteger) value; } return N.convert(value, BigInteger.class); } /** * * * @param key * @return */ public BigDecimal getBigDecimal(Object key) { Object value = map.get(key); if (value == null || value instanceof BigDecimal) { return (BigDecimal) value; } return N.convert(value, BigDecimal.class); } /** * * * @param key * @return */ public String getString(Object key) { Object value = map.get(key); if (value == null || value instanceof String) { return (String) value; } return N.stringOf(value); } /** * * * @param key * @return */ public Calendar getCalendar(Object key) { Object value = map.get(key); if (value == null || value instanceof Calendar) { return (Calendar) value; } return N.convert(value, Calendar.class); } /** * * * @param key * @return */ public Date getJUDate(Object key) { Object value = map.get(key); if (value == null || value instanceof Date) { return (Date) value; } return N.convert(value, Date.class); } /** * * * @param key * @return */ public java.sql.Date getDate(Object key) { Object value = map.get(key); if (value == null || value instanceof java.sql.Date) { return (java.sql.Date) value; } return N.convert(value, java.sql.Date.class); } /** * * * @param key * @return */ public java.sql.Time getTime(Object key) { Object value = map.get(key); if (value == null || value instanceof java.sql.Time) { return (java.sql.Time) value; } return N.convert(value, java.sql.Time.class); } /** * * * @param key * @return */ public java.sql.Timestamp getTimestamp(Object key) { Object value = map.get(key); if (value == null || value instanceof java.sql.Timestamp) { return (java.sql.Timestamp) value; } return N.convert(value, java.sql.Timestamp.class); } /** * * * @param key * @return */ public LocalDate getLocalDate(Object key) { Object value = map.get(key); if (value == null || value instanceof LocalDate) { return (LocalDate) value; } return N.convert(value, LocalDate.class); } /** * * * @param key * @return */ public LocalTime getLocalTime(Object key) { Object value = map.get(key); if (value == null || value instanceof LocalTime) { return (LocalTime) value; } return N.convert(value, LocalTime.class); } /** * * * @param key * @return */ public LocalDateTime getLocalDateTime(Object key) { Object value = map.get(key); if (value == null || value instanceof LocalDateTime) { return (LocalDateTime) value; } return N.convert(value, LocalDateTime.class); } /** * * * @param key * @return */ public ZonedDateTime getZonedDateTime(Object key) { Object value = map.get(key); if (value == null || value instanceof ZonedDateTime) { return (ZonedDateTime) value; } return N.convert(value, ZonedDateTime.class); } /** * * * @param key * @return */ public Object getObject(Object key) { return map.get(key); } /** * Returns {@code null} if no value found by the specified {@code key}, or the value is {@code null}. * *
* Node: To follow one of general design rules in {@code Abacus}, if there is a conversion behind when the source value is not assignable to the target type, put the {@code targetType} to last parameter of the method. * Otherwise, put the {@code targetTpye} to the first parameter of the method. * * @param * @param key * @param targetType * @return */ public T get(Object key, Class targetType) { final V val = map.get(key); if (val == null || targetType.isAssignableFrom(val.getClass())) { return (T) val; } return N.convert(val, targetType); } /** * Returns {@code null} if no value found by the specified {@code key}, or the value is {@code null}. * *
* Node: To follow one of general design rules in {@code Abacus}, if there is a conversion behind when the source value is not assignable to the target type, put the {@code targetType} to last parameter of the method. * Otherwise, put the {@code targetTpye} to the first parameter of the method. * * @param * @param key * @param targetType * @return */ public T get(Object key, Type targetType) { final V val = map.get(key); if (val == null || targetType.clazz().isAssignableFrom(val.getClass())) { return (T) val; } return N.convert(val, targetType); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy