All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.google.common.base.Functions Maven / Gradle / Ivy

Go to download

Google Collections Library is a suite of new collections and collection-related goodness for Java 5.0

The newest version!
/*
 * Copyright (C) 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.base;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.Serializable;
import java.util.Map;

/**
 * Useful functions.
 *
 * @author Mike Bostock
 * @author Vlad Patryshev
 * @author Jared Levy
 */
public final class Functions {
  private Functions() { }

  /**
   * See {@link #toStringFunction()}.
   *
   * TODO: Consider deprecating this in favor of an accessor method like
   * {@link #toStringFunction()}.
   */
  public static final Function TO_STRING =
      ToStringFunction.INSTANCE;

  /**
   * Returns a function that returns the {@link Object#toString} value of its
   * argument. This function is not nullable; invoking {@code apply(null)} on it
   * throws a {@link NullPointerException}.
   */
  @SuppressWarnings("unchecked") // see comment below
  public static  Function toStringFunction() {
    /*
     * Function is contravariant on F, so this is essentially a widening
     * cast. Note: IntelliJ incorrectly colors the following line red.
     */
    return (Function) ToStringFunction.INSTANCE;
  }

  // enum singleton pattern
  private enum ToStringFunction implements Function {
    INSTANCE;

    public String apply(Object o) {
      return o.toString();
    }

    @Override public String toString() {
      return "toString";
    }
  }

  /**
   * Returns a function that determines the {@link Object#hashCode()} of its
   * argument. For null arguments, this returns 0, as used in hash code
   * calculations by the Java Collections classes.
   */
  public static Function toHashCode() {
    return HashCodeFunction.INSTANCE;
  }

  // enum singleton pattern
  private enum HashCodeFunction implements Function {
    INSTANCE;

    public Integer apply(Object o) {
      return (o == null) ? 0 : o.hashCode();
    }

    @Override public String toString() {
      return "hashCode";
    }
  }
  
  /**
   * See {@link #trimString()}.
   *
   * TODO: Deprecate this and use trimString().
   */
  public static final Function TRIM_STRING =
      TrimStringFunction.INSTANCE;

  /**
   * A function that returns the result of calling {@link String#trim}
   * on its argument. Note that this function is not {@literal @Nullable}:
   * it will throw a {@link NullPointerException} when applied to {@code null}.
   */
  public static Function trimString() {
    return TrimStringFunction.INSTANCE;
  }

  // enum singleton pattern
  private enum TrimStringFunction implements Function {
    INSTANCE;

    public String apply(String string) {
      return string.trim();
    }

    @Override public String toString() {
      return "String.trim";
    }
  }
  
  /**
   * Returns the identity function.
   */
  @SuppressWarnings("unchecked")
  public static  Function identity() {
    return (Function) IdentityFunction.INSTANCE;
  }

  // enum singleton pattern
  private enum IdentityFunction implements Function {
    INSTANCE;

    public Object apply(Object o) {
      return o;
    }

    @Override public String toString() {
      return "identity";
    }
  }

  /**
   * Returns a function which performs key-to-value lookup on {@code map}.
   *
   * 

The difference between a map and a function is that a map is defined on * a set of keys, while a function is defined on a type. * The function built by this method returns {@code null} * for all arguments that do not belong to the map's keyset. * * @param map Map<A,B> source map * @return Function<A,B> function that returns map.get(a) for each A a */ public static Function forMap( final Map map) { return new FunctionForMapNoDefault(map); } private static class FunctionForMapNoDefault implements SerializableFunction { private final Map map; public FunctionForMapNoDefault( Map map) { this.map = checkNotNull(map); } public B apply(A a) { return map.get(a); } @Override public boolean equals(Object o) { if (o instanceof FunctionForMapNoDefault) { FunctionForMapNoDefault that = (FunctionForMapNoDefault) o; return map.equals(that.map); } return false; } @Override public int hashCode() { return map.hashCode(); } @Override public String toString() { return "forMap(" + map + ")"; } private static final long serialVersionUID = 3270419028101751025L; } /** * Returns a function which performs key-to-value lookup on {@code map}. * The function built by this method returns {@code defaultValue} * for all its arguments that do not belong to the map's keyset. * * @param map Map<A,B> * @param defaultValue B * @return Function {@code f} such that {@code f(a)=map.get(a)} * if {@code map.containsKey(x)}, and {@code defaultValue} otherwise. * * @see #forMap(Map) */ public static Function forMap( final Map map, @Nullable final B defaultValue) { if (defaultValue == null) { return forMap(map); } return new ForMapWithDefault(map, defaultValue); } private static class ForMapWithDefault implements SerializableFunction { private static final long serialVersionUID = 1652422010500531299L; private final Map map; private final B defaultValue; public ForMapWithDefault(Map map, B defaultValue) { this.map = checkNotNull(map); this.defaultValue = checkNotNull(defaultValue); } public B apply(A a) { return map.containsKey(a) ? map.get(a) : defaultValue; } @Override public boolean equals(Object o) { if (o instanceof ForMapWithDefault) { ForMapWithDefault that = (ForMapWithDefault) o; return map.equals(that.map) && defaultValue.equals(that.defaultValue); } return false; } @Override public int hashCode() { return map.hashCode() + defaultValue.hashCode(); } @Override public String toString() { return "forMap(" + map + ", defaultValue=" + defaultValue + ")"; } } /** * Returns the composition of two functions. For {@code f: A->B} and * {@code g: B->C}, composition is defined as the function h such that * {@code h(x) == g(f(x))} for each {@code x}. * * @see * function composition * * @param g Function<B,C> * @param f Function<A,B> * @return Function<A,C> composition of f and g */ public static Function compose( final Function g, final Function f) { return new FunctionComposition(g, f); } private static class FunctionComposition implements SerializableFunction { private final Function g; private final Function f; public FunctionComposition(Function g, Function f) { this.g = checkNotNull(g); this.f = checkNotNull(f); } public C apply(A a) { return g.apply(f.apply(a)); } @Override public boolean equals(Object obj) { if (obj instanceof FunctionComposition) { FunctionComposition that = (FunctionComposition) obj; return f.equals(that.f) && g.equals(that.g); } return false; } @Override public int hashCode() { /* * TODO: To leave the door open for future enhancement, this * calculation should be coordinated with the hashCode() method of the * corresponding composition method in Predicates. To construct the * composition: * predicate(function2(function1(x))) * * There are two different ways of composing it: * compose(predicate, compose(function2, function1)) * compose(compose(predicate, function2), function1) * * It would be nice if these could be equal. */ return f.hashCode() ^ g.hashCode(); } @Override public String toString() { return g.toString() + "(" + f.toString() + ")"; } private static final long serialVersionUID = 2530922454216511764L; } /** * Returns a boolean-valued function that evaluates to the same result as the * given predicate. */ public static Function forPredicate( Predicate predicate) { checkNotNull(predicate); return new PredicateFunction(predicate); } /** @see Functions#forPredicate */ private static class PredicateFunction implements SerializableFunction { private final Predicate predicate; private PredicateFunction(Predicate predicate) { this.predicate = checkNotNull(predicate); } public Boolean apply(T t) { return predicate.apply(t); } @Override public boolean equals(Object obj) { if (obj instanceof PredicateFunction) { PredicateFunction that = (PredicateFunction) obj; return predicate.equals(that.predicate); } return false; } @Override public int hashCode() { return predicate.hashCode(); } @Override public String toString() { return "asFunction(" + predicate + ")"; } private static final long serialVersionUID = 7159925838099303368L; } /** * Returns a {@link Function} that returns {@code value} for any input. * * @param value the constant value for the {@code Function} to return * @return a {@code Function} that always returns {@code value}. */ public static Function constant(@Nullable final E value) { return new ConstantFunction(value); } private static class ConstantFunction implements SerializableFunction { private static final long serialVersionUID = 2347134351918525179L; private final E value; public ConstantFunction(@Nullable E value) { this.value = value; } public E apply(Object from) { return value; } @Override public boolean equals(Object obj) { if (obj instanceof ConstantFunction) { ConstantFunction that = (ConstantFunction) obj; return Objects.equal(value, that.value); } return false; } @Override public int hashCode() { return (value == null) ? 0 : value.hashCode(); } @Override public String toString() { return "constant(" + value + ")"; } } private interface SerializableFunction extends Function, Serializable {} }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy