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