• 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 javax.annotation.CheckForNull;
26 import org.checkerframework.checker.nullness.qual.Nullable;
27 
28 /**
29  * An ordering that orders elements by applying an order to the result of a function on those
30  * elements.
31  */
32 @GwtCompatible(serializable = true)
33 @ElementTypesAreNonnullByDefault
34 final class ByFunctionOrdering<F extends @Nullable Object, T extends @Nullable Object>
35     extends Ordering<F> implements Serializable {
36   final Function<F, ? extends T> function;
37   final Ordering<T> ordering;
38 
ByFunctionOrdering(Function<F, ? extends T> function, Ordering<T> ordering)39   ByFunctionOrdering(Function<F, ? extends T> function, Ordering<T> ordering) {
40     this.function = checkNotNull(function);
41     this.ordering = checkNotNull(ordering);
42   }
43 
44   @Override
compare(@arametricNullness F left, @ParametricNullness F right)45   public int compare(@ParametricNullness F left, @ParametricNullness F right) {
46     return ordering.compare(function.apply(left), function.apply(right));
47   }
48 
49   @Override
equals(@heckForNull Object object)50   public boolean equals(@CheckForNull Object object) {
51     if (object == this) {
52       return true;
53     }
54     if (object instanceof ByFunctionOrdering) {
55       ByFunctionOrdering<?, ?> that = (ByFunctionOrdering<?, ?>) object;
56       return this.function.equals(that.function) && this.ordering.equals(that.ordering);
57     }
58     return false;
59   }
60 
61   @Override
hashCode()62   public int hashCode() {
63     return Objects.hashCode(function, ordering);
64   }
65 
66   @Override
toString()67   public String toString() {
68     return ordering + ".onResultOf(" + function + ")";
69   }
70 
71   private static final long serialVersionUID = 0;
72 }
73