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