1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.collections15.functors.transformer;
17
18 import net.sf.collections15.Transformer;
19
20 import java.io.Serializable;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.Map;
24
25
26 /***
27 * <code>Transformer</code> implementation whose {@link #transform} method
28 * derives an output object from an input object using a <code>Map</code>
29 * lookup.
30 *
31 * @author Stephen Colebourne
32 * @author Chris Lambrou (port to Java 5.0)
33 * @since Collections15 1.0
34 */
35 public final class MapTransformer <I, O> implements Transformer<I, O>, Serializable
36 {
37
38 static final long serialVersionUID = 8326978686026983067L;
39
40 /***
41 * The <code>Map</code> used to perform the transform lookup.
42 */
43 private final Map<? extends I, ? extends O> map;
44
45 /***
46 * Creates a new instance that uses the mappings of the specified
47 * <code>Map</code>.
48 *
49 * @param map The lookup mappings to be used by the new instance. The
50 * mappings of this <code>Map</code> are defensively copied.
51 *
52 * @return A new instance that uses the mappings of the specified
53 * <code>Map</code>.
54 *
55 * @throws IllegalArgumentException Thrown if the specified <code>Map</code>
56 * is <code>null</code>.
57 */
58 public static <I, O> MapTransformer<I, O> getInstance(Map<? extends I, ? extends O> map)
59 {
60 return new MapTransformer<I, O>(map);
61 }
62
63 /***
64 * Creates a new instance that uses the mappings of the specified
65 * <code>Map</code>.
66 *
67 * @param map The lookup mappings to be used by the new instance. The
68 * mappings of this <code>Map</code> are defensively copied.
69 *
70 * @throws IllegalArgumentException Thrown if the specified <code>Map</code>
71 * is <code>null</code>.
72 */
73 protected MapTransformer(Map<? extends I, ? extends O> map)
74 {
75 if (map == null) {
76 throw new IllegalArgumentException("null map specified");
77 }
78 this.map = new HashMap<I, O>(map);
79 }
80
81 /***
82 * Transforms the input to result by looking it up in a <code>Map</code>.
83 *
84 * @param input The input object to transform.
85 *
86 * @return The value that the input object is mapped to, or
87 * <code>null</code> if there is no mapped value, in accordance with
88 * the <code>Map</code> interface.
89 */
90 public O transform(I input)
91 {
92 return map.get(input);
93 }
94
95 /***
96 * A <code>Map</code> view of the mappings used by this
97 * <code>MapTransformer</code> instance.
98 *
99 * @return An unmodifiable <code>Map</code> view of the mappings used by
100 * this <code>MapTransformer</code> instance.
101 *
102 * @since Collections15 1.0
103 */
104 public Map<? extends I, ? extends O> getMap()
105 {
106 return Collections.unmodifiableMap(map);
107 }
108
109 }