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