01: /*
02: * Copyright 2001-2004 The Apache Software Foundation
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.apache.commons.collections.functors;
17:
18: import java.io.Serializable;
19: import java.util.Map;
20:
21: import org.apache.commons.collections.Transformer;
22:
23: /**
24: * Transformer implementation that returns the value held in a specified map
25: * using the input parameter as a key.
26: *
27: * @since Commons Collections 3.0
28: * @version $Revision: 348444 $ $Date: 2005-11-23 14:06:56 +0000 (Wed, 23 Nov 2005) $
29: *
30: * @author Stephen Colebourne
31: */
32: public final class MapTransformer implements Transformer, Serializable {
33:
34: /** Serial version UID */
35: private static final long serialVersionUID = 862391807045468939L;
36:
37: /** The map of data to lookup in */
38: private final Map iMap;
39:
40: /**
41: * Factory to create the transformer.
42: * <p>
43: * If the map is null, a transformer that always returns null is returned.
44: *
45: * @param map the map, not cloned
46: * @return the transformer
47: */
48: public static Transformer getInstance(Map map) {
49: if (map == null) {
50: return ConstantTransformer.NULL_INSTANCE;
51: }
52: return new MapTransformer(map);
53: }
54:
55: /**
56: * Constructor that performs no validation.
57: * Use <code>getInstance</code> if you want that.
58: *
59: * @param map the map to use for lookup, not cloned
60: */
61: private MapTransformer(Map map) {
62: super ();
63: iMap = map;
64: }
65:
66: /**
67: * Transforms the input to result by looking it up in a <code>Map</code>.
68: *
69: * @param input the input object to transform
70: * @return the transformed result
71: */
72: public Object transform(Object input) {
73: return iMap.get(input);
74: }
75:
76: /**
77: * Gets the map to lookup in.
78: *
79: * @return the map
80: * @since Commons Collections 3.1
81: */
82: public Map getMap() {
83: return iMap;
84: }
85:
86: }
|