    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.collections4.map;
    018
    019import java.io.IOException;
    020import java.io.ObjectInputStream;
    021import java.io.ObjectOutputStream;
    022import java.io.Serializable;
    023import java.util.HashMap;
    024import java.util.Map;
    025import java.util.Objects;
    026
    027import org.apache.commons.collections4.Factory;
    028import org.apache.commons.collections4.Transformer;
    029import org.apache.commons.collections4.functors.ConstantTransformer;
    030import org.apache.commons.collections4.functors.FactoryTransformer;
    031
    032/**
    033 * Decorates another {@code Map} returning a default value if the map
    034 * does not contain the requested key.
    035 * <p>
    036 * When the {@link #get(Object)} method is called with a key that does not
    037 * exist in the map, this map will return the default value specified in
    038 * the constructor/factory. Only the get method is altered, so the
    039 * {@link Map#containsKey(Object)} can be used to determine if a key really
    040 * is in the map or not.
    041 * </p>
    042 * <p>
    043 * The defaulted value is not added to the map.
    044 * Compare this behavior with {@link LazyMap}, which does add the value
    045 * to the map (via a Transformer).
    046 * </p>
    047 * <p>
    048 * For instance:
    049 * </p>
    050 * <pre>
    051 * Map map = new DefaultedMap("NULL");
    052 * Object obj = map.get("Surname");
    053 * // obj == "NULL"
    054 * </pre>
    055 * <p>
    056 * After the above code is executed the map is still empty.
    057 * </p>
    058 * <p>
    059 * <strong>Note that DefaultedMap is not synchronized and is not thread-safe.</strong>
    060 * If you wish to use this map from multiple threads concurrently, you must use
    061 * appropriate synchronization. The simplest approach is to wrap this map
    062 * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw
    063 * exceptions when accessed by concurrent threads without synchronization.
    064 * </p>
    065 *
    066 * @param <K> The type of the keys in this map
    067 * @param <V> The type of the values in this map
    068 * @since 3.2
    069 * @see LazyMap
    070 */
    071public class DefaultedMap<K, V> extends AbstractMapDecorator<K, V> implements Serializable {
    072
    073    /** Serialization version */
    074    private static final long serialVersionUID = 19698628745827L;
    075
    076    /**
    077     * Factory method to create a defaulting map.
    078     * <p>
    079     * The factory specified is called when a missing key is found.
    080     * The result will be returned as the result of the map get(key) method.
    081     *
    082     * @param <K>  the key type
    083     * @param <V>  the value type
    084     * @param map  The map to decorate, must not be null
    085     * @param factory  The factory to use to create entries, must not be null
    086     * @return A new defaulting map
    087     * @throws NullPointerException if map or factory is null
    088     * @since 4.0
    089     */
    090    public static <K, V> DefaultedMap<K, V> defaultedMap(final Map<K, V> map, final Factory<? extends V> factory) {
    091        return new DefaultedMap<>(map, FactoryTransformer.factoryTransformer(
    092                Objects.requireNonNull(factory, "Factory must not be null")));
    093    }
    094
    095    /**
    096     * Factory method to create a defaulting map.
    097     * <p>
    098     * The transformer specified is called when a missing key is found.
    099     * The key is passed to the transformer as the input, and the result
    100     * will be returned as the result of the map get(key) method.
    101     * </p>
    102     *
    103     * @param <K>  the key type
    104     * @param <V>  the value type
    105     * @param map  The map to decorate, must not be null
    106     * @param transformer  The transformer to use as a factory to create entries, must not be null
    107     * @return A new defaulting map
    108     * @throws NullPointerException if map or transformer is null
    109     * @since 4.0
    110     */
    111    public static <K, V> Map<K, V> defaultedMap(final Map<K, V> map,
    112                                                final Transformer<? super K, ? extends V> transformer) {
    113        return new DefaultedMap<>(map, Objects.requireNonNull(transformer, "Transformer must not be null"));
    114    }
    115
    116    /**
    117     * Factory method to create a defaulting map.
    118     * <p>
    119     * The value specified is returned when a missing key is found.
    120     * </p>
    121     *
    122     * @param <K>  the key type
    123     * @param <V>  the value type
    124     * @param map  The map to decorate, must not be null
    125     * @param defaultValue  The default value to return when the key is not found
    126     * @return A new defaulting map
    127     * @throws NullPointerException if map is null
    128     * @since 4.0
    129     */
    130    public static <K, V> DefaultedMap<K, V> defaultedMap(final Map<K, V> map, final V defaultValue) {
    131        return new DefaultedMap<>(map, ConstantTransformer.constantTransformer(defaultValue));
    132    }
    133
    134    /** The transformer to use if the map does not contain a key */
    135    private final Transformer<? super K, ? extends V> value;
    136
    137    /**
    138     * Constructor that wraps (not copies).
    139     *
    140     * @param map  The map to decorate, must not be null
    141     * @param defaultValueTransformer  The value transformer to use
    142     * @throws NullPointerException if map or transformer is null
    143     */
    144    protected DefaultedMap(final Map<K, V> map, final Transformer<? super K, ? extends V> defaultValueTransformer) {
    145        super(map);
    146        this.value = Objects.requireNonNull(defaultValueTransformer, "defaultValueTransformer");
    147    }
    148
    149    /**
    150     * Constructs a new empty {@code DefaultedMap} that decorates a {@code HashMap}.
    151     *
    152     * @param defaultValueTransformer transformer to use to generate missing values.
    153     */
    154    public DefaultedMap(final Transformer<? super K, ? extends V> defaultValueTransformer) {
    155        this(new HashMap<>(), defaultValueTransformer);
    156    }
    157
    158    /**
    159     * Constructs a new empty {@code DefaultedMap} that decorates
    160     * a {@code HashMap}.
    161     * <p>
    162     * The object passed in will be returned by the map whenever an
    163     * unknown key is requested.
    164     * </p>
    165     *
    166     * @param defaultValue  The default value to return when the key is not found
    167     */
    168    public DefaultedMap(final V defaultValue) {
    169        this(ConstantTransformer.constantTransformer(defaultValue));
    170    }
    171
    172    @Override
    173    @SuppressWarnings("unchecked")
    174    public V get(final Object key) {
    175        final V v;
    176        return (v = map.get(key)) != null || map.containsKey(key)
    177            ? v
    178            : value.apply((K) key);
    179    }
    180
    181    /**
    182     * Deserializes the map in using a custom routine.
    183     *
    184     * @param in  The input stream
    185     * @throws IOException Thrown if an error occurs while reading from the stream
    186     * @throws ClassNotFoundException if an object read from the stream cannot be loaded
    187     */
    188    @SuppressWarnings("unchecked")
    189    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    190        in.defaultReadObject();
    191        map = (Map<K, V>) in.readObject();
    192    }
    193
    194    /**
    195     * Serializes this object to an ObjectOutputStream.
    196     *
    197     * @param out The target ObjectOutputStream.
    198     * @throws IOException thrown when an I/O errors occur writing to the target stream.
    199     */
    200    private void writeObject(final ObjectOutputStream out) throws IOException {
    201        out.defaultWriteObject();
    202        out.writeObject(map);
    203    }
    204
    205    // no need to wrap keySet, entrySet or values as they are views of
    206    // existing map entries - you can't do a map-style get on them.
    207}