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.collections.functors;
18
19 import java.io.Serializable;
20 import java.util.Map;
21
22 import org.apache.commons.collections.Transformer;
23
24 /**
25 * Transformer implementation that returns the value held in a specified map
26 * using the input parameter as a key.
27 *
28 * @since 3.0
29 * @version $Id: MapTransformer.java 1435965 2013-01-20 21:13:18Z tn $
30 */
31 public final class MapTransformer<I, O> implements Transformer<I, O>, Serializable {
32
33 /** Serial version UID */
34 private static final long serialVersionUID = 862391807045468939L;
35
36 /** The map of data to lookup in */
37 private final Map<? super I, ? extends O> iMap;
38
39 /**
40 * Factory to create the transformer.
41 * <p>
42 * If the map is null, a transformer that always returns null is returned.
43 *
44 * @param <I> the input type
45 * @param <O> the output type
46 * @param map the map, not cloned
47 * @return the transformer
48 */
49 public static <I, O> Transformer<I, O> mapTransformer(final Map<? super I, ? extends O> map) {
50 if (map == null) {
51 return ConstantTransformer.<I, O>nullTransformer();
52 }
53 return new MapTransformer<I, O>(map);
54 }
55
56 /**
57 * Constructor that performs no validation.
58 * Use <code>getInstance</code> if you want that.
59 *
60 * @param map the map to use for lookup, not cloned
61 */
62 private MapTransformer(final Map<? super I, ? extends O> map) {
63 super();
64 iMap = map;
65 }
66
67 /**
68 * Transforms the input to result by looking it up in a <code>Map</code>.
69 *
70 * @param input the input object to transform
71 * @return the transformed result
72 */
73 public O transform(final I input) {
74 return iMap.get(input);
75 }
76
77 /**
78 * Gets the map to lookup in.
79 *
80 * @return the map
81 * @since 3.1
82 */
83 public Map<? super I, ? extends O> getMap() {
84 return iMap;
85 }
86
87 }