001 /*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package com.google.common.base;
018
019 import static com.google.common.base.Preconditions.checkArgument;
020 import static com.google.common.base.Preconditions.checkNotNull;
021
022 import com.google.common.annotations.Beta;
023 import com.google.common.annotations.GwtCompatible;
024
025 import java.io.Serializable;
026 import java.util.Map;
027
028 import javax.annotation.Nullable;
029
030 /**
031 * Static utility methods pertaining to {@code Function} instances.
032 *
033 * <p>All methods return serializable functions as long as they're given serializable parameters.
034 *
035 * <p>See the Guava User Guide article on <a href=
036 * "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the use of {@code
037 * Function}</a>.
038 *
039 * @author Mike Bostock
040 * @author Jared Levy
041 * @since 2.0 (imported from Google Collections Library)
042 */
043 @GwtCompatible
044 public final class Functions {
045 private Functions() {}
046
047 /**
048 * Returns a function that calls {@code toString()} on its argument. The function does not accept
049 * nulls; it will throw a {@link NullPointerException} when applied to {@code null}.
050 *
051 * <p><b>Warning:</b> The returned function may not be <i>consistent with equals</i> (as
052 * documented at {@link Function#apply}). For example, this function yields different results for
053 * the two equal instances {@code ImmutableSet.of(1, 2)} and {@code ImmutableSet.of(2, 1)}.
054 */
055 public static Function<Object, String> toStringFunction() {
056 return ToStringFunction.INSTANCE;
057 }
058
059 // enum singleton pattern
060 private enum ToStringFunction implements Function<Object, String> {
061 INSTANCE;
062
063 @Override
064 public String apply(Object o) {
065 checkNotNull(o); // eager for GWT.
066 return o.toString();
067 }
068
069 @Override public String toString() {
070 return "toString";
071 }
072 }
073
074 /**
075 * Returns the identity function.
076 */
077 @SuppressWarnings("unchecked")
078 public static <E> Function<E, E> identity() {
079 return (Function<E, E>) IdentityFunction.INSTANCE;
080 }
081
082 // enum singleton pattern
083 private enum IdentityFunction implements Function<Object, Object> {
084 INSTANCE;
085
086 @Override
087 public Object apply(Object o) {
088 return o;
089 }
090
091 @Override public String toString() {
092 return "identity";
093 }
094 }
095
096 /**
097 * Returns a function which performs a map lookup. The returned function throws an {@link
098 * IllegalArgumentException} if given a key that does not exist in the map.
099 */
100 public static <K, V> Function<K, V> forMap(Map<K, V> map) {
101 return new FunctionForMapNoDefault<K, V>(map);
102 }
103
104 private static class FunctionForMapNoDefault<K, V> implements Function<K, V>, Serializable {
105 final Map<K, V> map;
106
107 FunctionForMapNoDefault(Map<K, V> map) {
108 this.map = checkNotNull(map);
109 }
110
111 @Override
112 public V apply(K key) {
113 V result = map.get(key);
114 checkArgument(result != null || map.containsKey(key), "Key '%s' not present in map", key);
115 return result;
116 }
117
118 @Override public boolean equals(@Nullable Object o) {
119 if (o instanceof FunctionForMapNoDefault) {
120 FunctionForMapNoDefault<?, ?> that = (FunctionForMapNoDefault<?, ?>) o;
121 return map.equals(that.map);
122 }
123 return false;
124 }
125
126 @Override public int hashCode() {
127 return map.hashCode();
128 }
129
130 @Override public String toString() {
131 return "forMap(" + map + ")";
132 }
133
134 private static final long serialVersionUID = 0;
135 }
136
137 /**
138 * Returns a function which performs a map lookup with a default value. The function created by
139 * this method returns {@code defaultValue} for all inputs that do not belong to the map's key
140 * set.
141 *
142 * @param map source map that determines the function behavior
143 * @param defaultValue the value to return for inputs that aren't map keys
144 * @return function that returns {@code map.get(a)} when {@code a} is a key, or {@code
145 * defaultValue} otherwise
146 */
147 public static <K, V> Function<K, V> forMap(Map<K, ? extends V> map, @Nullable V defaultValue) {
148 return new ForMapWithDefault<K, V>(map, defaultValue);
149 }
150
151 private static class ForMapWithDefault<K, V> implements Function<K, V>, Serializable {
152 final Map<K, ? extends V> map;
153 final V defaultValue;
154
155 ForMapWithDefault(Map<K, ? extends V> map, @Nullable V defaultValue) {
156 this.map = checkNotNull(map);
157 this.defaultValue = defaultValue;
158 }
159
160 @Override
161 public V apply(K key) {
162 V result = map.get(key);
163 return (result != null || map.containsKey(key)) ? result : defaultValue;
164 }
165
166 @Override public boolean equals(@Nullable Object o) {
167 if (o instanceof ForMapWithDefault) {
168 ForMapWithDefault<?, ?> that = (ForMapWithDefault<?, ?>) o;
169 return map.equals(that.map) && Objects.equal(defaultValue, that.defaultValue);
170 }
171 return false;
172 }
173
174 @Override public int hashCode() {
175 return Objects.hashCode(map, defaultValue);
176 }
177
178 @Override public String toString() {
179 return "forMap(" + map + ", defaultValue=" + defaultValue + ")";
180 }
181
182 private static final long serialVersionUID = 0;
183 }
184
185 /**
186 * Returns the composition of two functions. For {@code f: A->B} and {@code g: B->C}, composition
187 * is defined as the function h such that {@code h(a) == g(f(a))} for each {@code a}.
188 *
189 * @param g the second function to apply
190 * @param f the first function to apply
191 * @return the composition of {@code f} and {@code g}
192 * @see <a href="//en.wikipedia.org/wiki/Function_composition">function composition</a>
193 */
194 public static <A, B, C> Function<A, C> compose(Function<B, C> g, Function<A, ? extends B> f) {
195 return new FunctionComposition<A, B, C>(g, f);
196 }
197
198 private static class FunctionComposition<A, B, C> implements Function<A, C>, Serializable {
199 private final Function<B, C> g;
200 private final Function<A, ? extends B> f;
201
202 public FunctionComposition(Function<B, C> g, Function<A, ? extends B> f) {
203 this.g = checkNotNull(g);
204 this.f = checkNotNull(f);
205 }
206
207 @Override
208 public C apply(A a) {
209 return g.apply(f.apply(a));
210 }
211
212 @Override public boolean equals(@Nullable Object obj) {
213 if (obj instanceof FunctionComposition) {
214 FunctionComposition<?, ?, ?> that = (FunctionComposition<?, ?, ?>) obj;
215 return f.equals(that.f) && g.equals(that.g);
216 }
217 return false;
218 }
219
220 @Override public int hashCode() {
221 return f.hashCode() ^ g.hashCode();
222 }
223
224 @Override public String toString() {
225 return g.toString() + "(" + f.toString() + ")";
226 }
227
228 private static final long serialVersionUID = 0;
229 }
230
231 /**
232 * Creates a function that returns the same boolean output as the given predicate for all inputs.
233 *
234 * <p>The returned function is <i>consistent with equals</i> (as documented at {@link
235 * Function#apply}) if and only if {@code predicate} is itself consistent with equals.
236 */
237 public static <T> Function<T, Boolean> forPredicate(Predicate<T> predicate) {
238 return new PredicateFunction<T>(predicate);
239 }
240
241 /** @see Functions#forPredicate */
242 private static class PredicateFunction<T> implements Function<T, Boolean>, Serializable {
243 private final Predicate<T> predicate;
244
245 private PredicateFunction(Predicate<T> predicate) {
246 this.predicate = checkNotNull(predicate);
247 }
248
249 @Override
250 public Boolean apply(T t) {
251 return predicate.apply(t);
252 }
253
254 @Override public boolean equals(@Nullable Object obj) {
255 if (obj instanceof PredicateFunction) {
256 PredicateFunction<?> that = (PredicateFunction<?>) obj;
257 return predicate.equals(that.predicate);
258 }
259 return false;
260 }
261
262 @Override public int hashCode() {
263 return predicate.hashCode();
264 }
265
266 @Override public String toString() {
267 return "forPredicate(" + predicate + ")";
268 }
269
270 private static final long serialVersionUID = 0;
271 }
272
273 /**
274 * Creates a function that returns {@code value} for any input.
275 *
276 * @param value the constant value for the function to return
277 * @return a function that always returns {@code value}
278 */
279 public static <E> Function<Object, E> constant(@Nullable E value) {
280 return new ConstantFunction<E>(value);
281 }
282
283 private static class ConstantFunction<E> implements Function<Object, E>, Serializable {
284 private final E value;
285
286 public ConstantFunction(@Nullable E value) {
287 this.value = value;
288 }
289
290 @Override
291 public E apply(@Nullable Object from) {
292 return value;
293 }
294
295 @Override public boolean equals(@Nullable Object obj) {
296 if (obj instanceof ConstantFunction) {
297 ConstantFunction<?> that = (ConstantFunction<?>) obj;
298 return Objects.equal(value, that.value);
299 }
300 return false;
301 }
302
303 @Override public int hashCode() {
304 return (value == null) ? 0 : value.hashCode();
305 }
306
307 @Override public String toString() {
308 return "constant(" + value + ")";
309 }
310
311 private static final long serialVersionUID = 0;
312 }
313
314 /**
315 * Returns a function that always returns the result of invoking {@link Supplier#get} on {@code
316 * supplier}, regardless of its input.
317 *
318 * @since 10.0
319 */
320 @Beta
321 public static <T> Function<Object, T> forSupplier(Supplier<T> supplier) {
322 return new SupplierFunction<T>(supplier);
323 }
324
325 /** @see Functions#forSupplier*/
326 private static class SupplierFunction<T> implements Function<Object, T>, Serializable {
327
328 private final Supplier<T> supplier;
329
330 private SupplierFunction(Supplier<T> supplier) {
331 this.supplier = checkNotNull(supplier);
332 }
333
334 @Override public T apply(@Nullable Object input) {
335 return supplier.get();
336 }
337
338 @Override public boolean equals(@Nullable Object obj) {
339 if (obj instanceof SupplierFunction) {
340 SupplierFunction<?> that = (SupplierFunction<?>) obj;
341 return this.supplier.equals(that.supplier);
342 }
343 return false;
344 }
345
346 @Override public int hashCode() {
347 return supplier.hashCode();
348 }
349
350 @Override public String toString() {
351 return "forSupplier(" + supplier + ")";
352 }
353
354 private static final long serialVersionUID = 0;
355 }
356 }