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