• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Guava Authors
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.collect;
18 
19 import static com.google.common.base.Preconditions.checkNotNull;
20 
21 import com.google.common.annotations.GwtCompatible;
22 import com.google.common.base.Function;
23 import com.google.common.base.Objects;
24 import java.io.Serializable;
25 import org.checkerframework.checker.nullness.compatqual.NullableDecl;
26 
27 /**
28  * An ordering that orders elements by applying an order to the result of a function on those
29  * elements.
30  */
31 @GwtCompatible(serializable = true)
32 final class ByFunctionOrdering<F, T> extends Ordering<F> implements Serializable {
33   final Function<F, ? extends T> function;
34   final Ordering<T> ordering;
35 
ByFunctionOrdering(Function<F, ? extends T> function, Ordering<T> ordering)36   ByFunctionOrdering(Function<F, ? extends T> function, Ordering<T> ordering) {
37     this.function = checkNotNull(function);
38     this.ordering = checkNotNull(ordering);
39   }
40 
41   @Override
compare(F left, F right)42   public int compare(F left, F right) {
43     return ordering.compare(function.apply(left), function.apply(right));
44   }
45 
46   @Override
equals(@ullableDecl Object object)47   public boolean equals(@NullableDecl Object object) {
48     if (object == this) {
49       return true;
50     }
51     if (object instanceof ByFunctionOrdering) {
52       ByFunctionOrdering<?, ?> that = (ByFunctionOrdering<?, ?>) object;
53       return this.function.equals(that.function) && this.ordering.equals(that.ordering);
54     }
55     return false;
56   }
57 
58   @Override
hashCode()59   public int hashCode() {
60     return Objects.hashCode(function, ordering);
61   }
62 
63   @Override
toString()64   public String toString() {
65     return ordering + ".onResultOf(" + function + ")";
66   }
67 
68   private static final long serialVersionUID = 0;
69 }
70