DefaultedMap.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.collections4.map;

  18. import java.io.IOException;
  19. import java.io.ObjectInputStream;
  20. import java.io.ObjectOutputStream;
  21. import java.io.Serializable;
  22. import java.util.HashMap;
  23. import java.util.Map;
  24. import java.util.Objects;

  25. import org.apache.commons.collections4.Factory;
  26. import org.apache.commons.collections4.Transformer;
  27. import org.apache.commons.collections4.functors.ConstantTransformer;
  28. import org.apache.commons.collections4.functors.FactoryTransformer;

  29. /**
  30.  * Decorates another {@code Map} returning a default value if the map
  31.  * does not contain the requested key.
  32.  * <p>
  33.  * When the {@link #get(Object)} method is called with a key that does not
  34.  * exist in the map, this map will return the default value specified in
  35.  * the constructor/factory. Only the get method is altered, so the
  36.  * {@link Map#containsKey(Object)} can be used to determine if a key really
  37.  * is in the map or not.
  38.  * </p>
  39.  * <p>
  40.  * The defaulted value is not added to the map.
  41.  * Compare this behavior with {@link LazyMap}, which does add the value
  42.  * to the map (via a Transformer).
  43.  * </p>
  44.  * <p>
  45.  * For instance:
  46.  * </p>
  47.  * <pre>
  48.  * Map map = new DefaultedMap("NULL");
  49.  * Object obj = map.get("Surname");
  50.  * // obj == "NULL"
  51.  * </pre>
  52.  * <p>
  53.  * After the above code is executed the map is still empty.
  54.  * </p>
  55.  * <p>
  56.  * <strong>Note that DefaultedMap is not synchronized and is not thread-safe.</strong>
  57.  * If you wish to use this map from multiple threads concurrently, you must use
  58.  * appropriate synchronization. The simplest approach is to wrap this map
  59.  * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw
  60.  * exceptions when accessed by concurrent threads without synchronization.
  61.  * </p>
  62.  *
  63.  * @param <K> the type of the keys in this map
  64.  * @param <V> the type of the values in this map
  65.  * @since 3.2
  66.  * @see LazyMap
  67.  */
  68. public class DefaultedMap<K, V> extends AbstractMapDecorator<K, V> implements Serializable {

  69.     /** Serialization version */
  70.     private static final long serialVersionUID = 19698628745827L;

  71.     /**
  72.      * Factory method to create a defaulting map.
  73.      * <p>
  74.      * The factory specified is called when a missing key is found.
  75.      * The result will be returned as the result of the map get(key) method.
  76.      *
  77.      * @param <K>  the key type
  78.      * @param <V>  the value type
  79.      * @param map  the map to decorate, must not be null
  80.      * @param factory  the factory to use to create entries, must not be null
  81.      * @return a new defaulting map
  82.      * @throws NullPointerException if map or factory is null
  83.      * @since 4.0
  84.      */
  85.     public static <K, V> DefaultedMap<K, V> defaultedMap(final Map<K, V> map, final Factory<? extends V> factory) {
  86.         return new DefaultedMap<>(map, FactoryTransformer.factoryTransformer(
  87.                 Objects.requireNonNull(factory, "Factory must not be null")));
  88.     }

  89.     /**
  90.      * Factory method to create a defaulting map.
  91.      * <p>
  92.      * The transformer specified is called when a missing key is found.
  93.      * The key is passed to the transformer as the input, and the result
  94.      * will be returned as the result of the map get(key) method.
  95.      * </p>
  96.      *
  97.      * @param <K>  the key type
  98.      * @param <V>  the value type
  99.      * @param map  the map to decorate, must not be null
  100.      * @param transformer  the transformer to use as a factory to create entries, must not be null
  101.      * @return a new defaulting map
  102.      * @throws NullPointerException if map or transformer is null
  103.      * @since 4.0
  104.      */
  105.     public static <K, V> Map<K, V> defaultedMap(final Map<K, V> map,
  106.                                                 final Transformer<? super K, ? extends V> transformer) {
  107.         return new DefaultedMap<>(map, Objects.requireNonNull(transformer, "Transformer must not be null"));
  108.     }

  109.     /**
  110.      * Factory method to create a defaulting map.
  111.      * <p>
  112.      * The value specified is returned when a missing key is found.
  113.      * </p>
  114.      *
  115.      * @param <K>  the key type
  116.      * @param <V>  the value type
  117.      * @param map  the map to decorate, must not be null
  118.      * @param defaultValue  the default value to return when the key is not found
  119.      * @return a new defaulting map
  120.      * @throws NullPointerException if map is null
  121.      * @since 4.0
  122.      */
  123.     public static <K, V> DefaultedMap<K, V> defaultedMap(final Map<K, V> map, final V defaultValue) {
  124.         return new DefaultedMap<>(map, ConstantTransformer.constantTransformer(defaultValue));
  125.     }

  126.     /** The transformer to use if the map does not contain a key */
  127.     private final Transformer<? super K, ? extends V> value;

  128.     /**
  129.      * Constructor that wraps (not copies).
  130.      *
  131.      * @param map  the map to decorate, must not be null
  132.      * @param defaultValueTransformer  the value transformer to use
  133.      * @throws NullPointerException if map or transformer is null
  134.      */
  135.     protected DefaultedMap(final Map<K, V> map, final Transformer<? super K, ? extends V> defaultValueTransformer) {
  136.         super(map);
  137.         this.value = Objects.requireNonNull(defaultValueTransformer, "defaultValueTransformer");
  138.     }

  139.     /**
  140.      * Constructs a new empty {@code DefaultedMap} that decorates a {@code HashMap}.
  141.      *
  142.      * @param defaultValueTransformer transformer to use to generate missing values.
  143.      */
  144.     public DefaultedMap(final Transformer<? super K, ? extends V> defaultValueTransformer) {
  145.         this(new HashMap<>(), defaultValueTransformer);
  146.     }

  147.     /**
  148.      * Constructs a new empty {@code DefaultedMap} that decorates
  149.      * a {@code HashMap}.
  150.      * <p>
  151.      * The object passed in will be returned by the map whenever an
  152.      * unknown key is requested.
  153.      * </p>
  154.      *
  155.      * @param defaultValue  the default value to return when the key is not found
  156.      */
  157.     public DefaultedMap(final V defaultValue) {
  158.         this(ConstantTransformer.constantTransformer(defaultValue));
  159.     }

  160.     @Override
  161.     @SuppressWarnings("unchecked")
  162.     public V get(final Object key) {
  163.         final V v;
  164.         return (v = map.get(key)) != null || map.containsKey(key)
  165.             ? v
  166.             : value.apply((K) key);
  167.     }

  168.     /**
  169.      * Deserializes the map in using a custom routine.
  170.      *
  171.      * @param in  the input stream
  172.      * @throws IOException if an error occurs while reading from the stream
  173.      * @throws ClassNotFoundException if an object read from the stream cannot be loaded
  174.      */
  175.     @SuppressWarnings("unchecked")
  176.     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
  177.         in.defaultReadObject();
  178.         map = (Map<K, V>) in.readObject();
  179.     }

  180.     /**
  181.      * Serializes this object to an ObjectOutputStream.
  182.      *
  183.      * @param out the target ObjectOutputStream.
  184.      * @throws IOException thrown when an I/O errors occur writing to the target stream.
  185.      */
  186.     private void writeObject(final ObjectOutputStream out) throws IOException {
  187.         out.defaultWriteObject();
  188.         out.writeObject(map);
  189.     }

  190.     // no need to wrap keySet, entrySet or values as they are views of
  191.     // existing map entries - you can't do a map-style get on them.
  192. }