Home | History | Annotate | Download | only in base
      1 /*
      2  * Copyright (C) 2007 Google Inc.
      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 
     17 package com.google.common.base;
     18 
     19 import com.google.common.annotations.GwtCompatible;
     20 import static com.google.common.base.Preconditions.checkArgument;
     21 import static com.google.common.base.Preconditions.checkNotNull;
     22 
     23 import java.io.Serializable;
     24 import java.util.Map;
     25 
     26 import javax.annotation.Nullable;
     27 
     28 /**
     29  * Useful functions.
     30  *
     31  * <p>All methods returns serializable functions as long as they're given
     32  * serializable parameters.
     33  *
     34  * @author Mike Bostock
     35  * @author Vlad Patryshev
     36  * @author Jared Levy
     37  * @since 2010.01.04 <b>stable</b> (imported from Google Collections Library)
     38  */
     39 @GwtCompatible
     40 public final class Functions {
     41   private Functions() {}
     42 
     43   /**
     44    * Returns a function that calls {@code toString()} on its argument. The
     45    * function does not accept nulls; it will throw a
     46    * {@link NullPointerException} when applied to {@code null}.
     47    */
     48   public static Function<Object, String> toStringFunction() {
     49     return ToStringFunction.INSTANCE;
     50   }
     51 
     52   // enum singleton pattern
     53   private enum ToStringFunction implements Function<Object, String> {
     54     INSTANCE;
     55 
     56     public String apply(Object o) {
     57       return o.toString();
     58     }
     59 
     60     @Override public String toString() {
     61       return "toString";
     62     }
     63   }
     64 
     65   /**
     66    * Returns the identity function.
     67    */
     68   @SuppressWarnings("unchecked")
     69   public static <E> Function<E, E> identity() {
     70     return (Function<E, E>) IdentityFunction.INSTANCE;
     71   }
     72 
     73   // enum singleton pattern
     74   private enum IdentityFunction implements Function<Object, Object> {
     75     INSTANCE;
     76 
     77     public Object apply(Object o) {
     78       return o;
     79     }
     80 
     81     @Override public String toString() {
     82       return "identity";
     83     }
     84   }
     85 
     86   /**
     87    * Returns a function which performs a map lookup. The returned function
     88    * throws an {@link IllegalArgumentException} if given a key that does not
     89    * exist in the map.
     90    */
     91   public static <K, V> Function<K, V> forMap(Map<K, V> map) {
     92     return new FunctionForMapNoDefault<K, V>(map);
     93   }
     94 
     95   private static class FunctionForMapNoDefault<K, V>
     96       implements Function<K, V>, Serializable {
     97     final Map<K, V> map;
     98 
     99     FunctionForMapNoDefault(Map<K, V> map) {
    100       this.map = checkNotNull(map);
    101     }
    102     public V apply(K key) {
    103       V result = map.get(key);
    104       checkArgument(result != null || map.containsKey(key),
    105           "Key '%s' not present in map", key);
    106       return result;
    107     }
    108     @Override public boolean equals(Object o) {
    109       if (o instanceof FunctionForMapNoDefault) {
    110         FunctionForMapNoDefault<?, ?> that = (FunctionForMapNoDefault<?, ?>) o;
    111         return map.equals(that.map);
    112       }
    113       return false;
    114     }
    115     @Override public int hashCode() {
    116       return map.hashCode();
    117     }
    118     @Override public String toString() {
    119       return "forMap(" + map + ")";
    120     }
    121     private static final long serialVersionUID = 0;
    122   }
    123 
    124   /**
    125    * Returns a function which performs a map lookup with a default value. The
    126    * function created by this method returns {@code defaultValue} for all
    127    * inputs that do not belong to the map's key set.
    128    *
    129    * @param map source map that determines the function behavior
    130    * @param defaultValue the value to return for inputs that aren't map keys
    131    * @return function that returns {@code map.get(a)} when {@code a} is a key,
    132    *     or {@code defaultValue} otherwise
    133    */
    134   public static <K, V> Function<K, V> forMap(
    135       Map<K, ? extends V> map, @Nullable V defaultValue) {
    136     return new ForMapWithDefault<K, V>(map, defaultValue);
    137   }
    138 
    139   private static class ForMapWithDefault<K, V>
    140       implements Function<K, V>, Serializable {
    141     final Map<K, ? extends V> map;
    142     final V defaultValue;
    143 
    144     ForMapWithDefault(Map<K, ? extends V> map, V defaultValue) {
    145       this.map = checkNotNull(map);
    146       this.defaultValue = defaultValue;
    147     }
    148     public V apply(K key) {
    149       return map.containsKey(key) ? map.get(key) : defaultValue;
    150     }
    151     @Override public boolean equals(Object o) {
    152       if (o instanceof ForMapWithDefault) {
    153         ForMapWithDefault<?, ?> that = (ForMapWithDefault<?, ?>) o;
    154         return map.equals(that.map)
    155             && Objects.equal(defaultValue, that.defaultValue);
    156       }
    157       return false;
    158     }
    159     @Override public int hashCode() {
    160       return Objects.hashCode(map, defaultValue);
    161     }
    162     @Override public String toString() {
    163       return "forMap(" + map + ", defaultValue=" + defaultValue + ")";
    164     }
    165     private static final long serialVersionUID = 0;
    166   }
    167 
    168   /**
    169    * Returns the composition of two functions. For {@code f: A->B} and
    170    * {@code g: B->C}, composition is defined as the function h such that
    171    * {@code h(a) == g(f(a))} for each {@code a}.
    172    *
    173    * @see <a href="//en.wikipedia.org/wiki/Function_composition">
    174    * function composition</a>
    175    *
    176    * @param g the second function to apply
    177    * @param f the first function to apply
    178    * @return the composition of {@code f} and {@code g}
    179    */
    180   public static <A, B, C> Function<A, C> compose(
    181       Function<B, C> g, Function<A, ? extends B> f) {
    182     return new FunctionComposition<A, B, C>(g, f);
    183   }
    184 
    185   private static class FunctionComposition<A, B, C>
    186       implements Function<A, C>, Serializable {
    187     private final Function<B, C> g;
    188     private final Function<A, ? extends B> f;
    189 
    190     public FunctionComposition(Function<B, C> g,
    191         Function<A, ? extends B> f) {
    192       this.g = checkNotNull(g);
    193       this.f = checkNotNull(f);
    194     }
    195     public C apply(A a) {
    196       return g.apply(f.apply(a));
    197     }
    198     @Override public boolean equals(Object obj) {
    199       if (obj instanceof FunctionComposition) {
    200         FunctionComposition<?, ?, ?> that = (FunctionComposition<?, ?, ?>) obj;
    201         return f.equals(that.f) && g.equals(that.g);
    202       }
    203       return false;
    204     }
    205 
    206     @Override public int hashCode() {
    207       return f.hashCode() ^ g.hashCode();
    208     }
    209     @Override public String toString() {
    210       return g.toString() + "(" + f.toString() + ")";
    211     }
    212     private static final long serialVersionUID = 0;
    213   }
    214 
    215   /**
    216    * Creates a function that returns the same boolean output as the given
    217    * predicate for all inputs.
    218    */
    219   public static <T> Function<T, Boolean> forPredicate(Predicate<T> predicate) {
    220     return new PredicateFunction<T>(predicate);
    221   }
    222 
    223   /** @see Functions#forPredicate */
    224   private static class PredicateFunction<T>
    225       implements Function<T, Boolean>, Serializable {
    226     private final Predicate<T> predicate;
    227 
    228     private PredicateFunction(Predicate<T> predicate) {
    229       this.predicate = checkNotNull(predicate);
    230     }
    231 
    232     public Boolean apply(T t) {
    233       return predicate.apply(t);
    234     }
    235     @Override public boolean equals(Object obj) {
    236       if (obj instanceof PredicateFunction) {
    237         PredicateFunction<?> that = (PredicateFunction<?>) obj;
    238         return predicate.equals(that.predicate);
    239       }
    240       return false;
    241     }
    242     @Override public int hashCode() {
    243       return predicate.hashCode();
    244     }
    245     @Override public String toString() {
    246       return "forPredicate(" + predicate + ")";
    247     }
    248     private static final long serialVersionUID = 0;
    249   }
    250 
    251   /**
    252    * Creates a function that returns {@code value} for any input.
    253    *
    254    * @param value the constant value for the function to return
    255    * @return a function that always returns {@code value}
    256    */
    257   public static <E> Function<Object, E> constant(@Nullable E value) {
    258     return new ConstantFunction<E>(value);
    259   }
    260 
    261   private static class ConstantFunction<E>
    262       implements Function<Object, E>, Serializable {
    263     private final E value;
    264 
    265     public ConstantFunction(@Nullable E value) {
    266       this.value = value;
    267     }
    268     public E apply(Object from) {
    269       return value;
    270     }
    271     @Override public boolean equals(Object obj) {
    272       if (obj instanceof ConstantFunction) {
    273         ConstantFunction<?> that = (ConstantFunction<?>) obj;
    274         return Objects.equal(value, that.value);
    275       }
    276       return false;
    277     }
    278     @Override public int hashCode() {
    279       return (value == null) ? 0 : value.hashCode();
    280     }
    281     @Override public String toString() {
    282       return "constant(" + value + ")";
    283     }
    284     private static final long serialVersionUID = 0;
    285   }
    286 }
    287