1. /*
  2. * Copyright 2001-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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. import java.io.Serializable;
  18. import java.util.Map;
  19. import org.apache.commons.collections.Transformer;
  20. /**
  21. * Transformer implementation that returns the value held in a specified map
  22. * using the input parameter as a key.
  23. *
  24. * @since Commons Collections 3.0
  25. * @version $Revision: 1.7 $ $Date: 2004/05/16 11:36:31 $
  26. *
  27. * @author Stephen Colebourne
  28. */
  29. public final class MapTransformer implements Transformer, Serializable {
  30. /** Serial version UID */
  31. static final long serialVersionUID = 862391807045468939L;
  32. /** The map of data to lookup in */
  33. private final Map iMap;
  34. /**
  35. * Factory to create the transformer.
  36. * <p>
  37. * If the map is null, a transformer that always returns null is returned.
  38. *
  39. * @param map the map, not cloned
  40. * @return the transformer
  41. */
  42. public static Transformer getInstance(Map map) {
  43. if (map == null) {
  44. return ConstantTransformer.NULL_INSTANCE;
  45. }
  46. return new MapTransformer(map);
  47. }
  48. /**
  49. * Constructor that performs no validation.
  50. * Use <code>getInstance</code> if you want that.
  51. *
  52. * @param map the map to use for lookup, not cloned
  53. */
  54. private MapTransformer(Map map) {
  55. super();
  56. iMap = map;
  57. }
  58. /**
  59. * Transforms the input to result by looking it up in a <code>Map</code>.
  60. *
  61. * @param input the input object to transform
  62. * @return the transformed result
  63. */
  64. public Object transform(Object input) {
  65. return iMap.get(input);
  66. }
  67. /**
  68. * Gets the map to lookup in.
  69. *
  70. * @return the map
  71. * @since Commons Collections 3.1
  72. */
  73. public Map getMap() {
  74. return iMap;
  75. }
  76. }