TransformedSplitMap.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.splitmap;

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

  24. import org.apache.commons.collections4.Put;
  25. import org.apache.commons.collections4.Transformer;
  26. import org.apache.commons.collections4.map.LinkedMap;

  27. /**
  28.  * Decorates another {@link Map} to transform objects that are added.
  29.  * <p>
  30.  * The Map put methods and Map.Entry setValue method are affected by this class.
  31.  * Thus objects must be removed or searched for using their transformed form.
  32.  * For example, if the transformation converts Strings to Integers, you must use
  33.  * the Integer form to remove objects.
  34.  * </p>
  35.  * <p>
  36.  * <strong>Note that TransformedMap is not synchronized and is not
  37.  * thread-safe.</strong> If you wish to use this map from multiple threads
  38.  * concurrently, you must use appropriate synchronization. The simplest approach
  39.  * is to wrap this map using {@link java.util.Collections#synchronizedMap(Map)}.
  40.  * This class may throw exceptions when accessed by concurrent threads without
  41.  * synchronization.
  42.  * </p>
  43.  * <p>
  44.  * The "put" and "get" type constraints of this class are mutually independent;
  45.  * contrast with {@link org.apache.commons.collections4.map.TransformedMap} which,
  46.  * by virtue of its implementing {@link Map}&lt;K, V&gt;, must be constructed in such
  47.  * a way that its read and write parameters are generalized to a common (super-)type.
  48.  * In practice this would often mean {@code &gt;Object, Object&gt;}, defeating
  49.  * much of the usefulness of having parameterized types.
  50.  * </p>
  51.  * <p>
  52.  * On the downside, this class is not drop-in compatible with {@link java.util.Map}
  53.  * but is intended to be worked with either directly or by {@link Put} and
  54.  * {@link org.apache.commons.collections4.Get Get} generalizations.
  55.  * </p>
  56.  *
  57.  * @param <J> the type of the keys to put in this map
  58.  * @param <K> the type of the keys to get in this map
  59.  * @param <U> the type of the values to put in this map
  60.  * @param <V> the type of the values to get in this map
  61.  * @since 4.0
  62.  * @see org.apache.commons.collections4.SplitMapUtils#readableMap(org.apache.commons.collections4.Get)
  63.  * @see org.apache.commons.collections4.SplitMapUtils#writableMap(Put)
  64.  */
  65. public class TransformedSplitMap<J, K, U, V> extends AbstractIterableGetMapDecorator<K, V>
  66.         implements Put<J, U>, Serializable {

  67.     /** Serialization version */
  68.     private static final long serialVersionUID = 5966875321133456994L;

  69.     /**
  70.      * Factory method to create a transforming map.
  71.      * <p>
  72.      * If there are any elements already in the map being decorated, they are
  73.      * NOT transformed.
  74.      *
  75.      * @param <J>  the input key type
  76.      * @param <K>  the output key type
  77.      * @param <U>  the input value type
  78.      * @param <V>  the output value type
  79.      * @param map the map to decorate, must not be null
  80.      * @param keyTransformer the transformer to use for key conversion, must not be null
  81.      * @param valueTransformer the transformer to use for value conversion, must not be null
  82.      * @return a new transformed map
  83.      * @throws NullPointerException if map or either of the transformers is null
  84.      */
  85.     public static <J, K, U, V> TransformedSplitMap<J, K, U, V> transformingMap(final Map<K, V> map,
  86.             final Transformer<? super J, ? extends K> keyTransformer,
  87.             final Transformer<? super U, ? extends V> valueTransformer) {
  88.         return new TransformedSplitMap<>(map, keyTransformer, valueTransformer);
  89.     }
  90.     /** The transformer to use for the key */
  91.     private final Transformer<? super J, ? extends K> keyTransformer;

  92.     /** The transformer to use for the value */
  93.     private final Transformer<? super U, ? extends V> valueTransformer;

  94.     /**
  95.      * Constructor that wraps (not copies).
  96.      * <p>
  97.      * If there are any elements already in the collection being decorated, they
  98.      * are NOT transformed.
  99.      *
  100.      * @param map the map to decorate, must not be null
  101.      * @param keyTransformer the transformer to use for key conversion, must not be null
  102.      * @param valueTransformer the transformer to use for value conversion, must not be null
  103.      * @throws NullPointerException if map or either of the transformers is null
  104.      */
  105.     protected TransformedSplitMap(final Map<K, V> map, final Transformer<? super J, ? extends K> keyTransformer,
  106.             final Transformer<? super U, ? extends V> valueTransformer) {
  107.         super(map);
  108.         this.keyTransformer = Objects.requireNonNull(keyTransformer, "keyTransformer");
  109.         this.valueTransformer = Objects.requireNonNull(valueTransformer, "valueTransformer");
  110.     }

  111.     /**
  112.      * Override to transform the value when using {@code setValue}.
  113.      *
  114.      * @param value the value to transform
  115.      * @return the transformed value
  116.      */
  117.     protected V checkSetValue(final U value) {
  118.         return valueTransformer.apply(value);
  119.     }

  120.     @Override
  121.     public void clear() {
  122.         decorated().clear();
  123.     }

  124.     @Override
  125.     public V put(final J key, final U value) {
  126.         return decorated().put(transformKey(key), transformValue(value));
  127.     }

  128.     @Override
  129.     public void putAll(final Map<? extends J, ? extends U> mapToCopy) {
  130.         decorated().putAll(transformMap(mapToCopy));
  131.     }

  132.     /**
  133.      * Deserializes the map in using a custom routine.
  134.      *
  135.      * @param in the input stream
  136.      * @throws IOException if an error occurs while reading from the stream
  137.      * @throws ClassNotFoundException if an object read from the stream cannot be loaded
  138.      * @since 3.1
  139.      */
  140.     @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect
  141.     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
  142.         in.defaultReadObject();
  143.         map = (Map<K, V>) in.readObject(); // (1)
  144.     }

  145.     /**
  146.      * Transforms a key.
  147.      * <p>
  148.      * The transformer itself may throw an exception if necessary.
  149.      *
  150.      * @param object the object to transform
  151.      * @return the transformed object
  152.      */
  153.     protected K transformKey(final J object) {
  154.         return keyTransformer.apply(object);
  155.     }

  156.     /**
  157.      * Transforms a map.
  158.      * <p>
  159.      * The transformer itself may throw an exception if necessary.
  160.      *
  161.      * @param map the map to transform
  162.      * @return the transformed object
  163.      */
  164.     @SuppressWarnings("unchecked")
  165.     protected Map<K, V> transformMap(final Map<? extends J, ? extends U> map) {
  166.         if (map.isEmpty()) {
  167.             return (Map<K, V>) map;
  168.         }
  169.         final Map<K, V> result = new LinkedMap<>(map.size());

  170.         for (final Map.Entry<? extends J, ? extends U> entry : map.entrySet()) {
  171.             result.put(transformKey(entry.getKey()), transformValue(entry.getValue()));
  172.         }
  173.         return result;
  174.     }

  175.     /**
  176.      * Transforms a value.
  177.      * <p>
  178.      * The transformer itself may throw an exception if necessary.
  179.      *
  180.      * @param object the object to transform
  181.      * @return the transformed object
  182.      */
  183.     protected V transformValue(final U object) {
  184.         return valueTransformer.apply(object);
  185.     }

  186.     /**
  187.      * Serializes this object to an ObjectOutputStream.
  188.      *
  189.      * @param out the target ObjectOutputStream.
  190.      * @throws IOException thrown when an I/O errors occur writing to the target stream.
  191.      */
  192.     private void writeObject(final ObjectOutputStream out) throws IOException {
  193.         out.defaultWriteObject();
  194.         out.writeObject(decorated());
  195.     }
  196. }