All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.lambda.query.OrderBy Maven / Gradle / Ivy

There is a newer version: 24.9.0
Show newest version
package org.lambda.query;

import org.lambda.functions.Function1;

import java.util.Comparator;

public class OrderBy> implements Comparator
{
  public static enum Order {
                            Ascending, Descending
  }
  private Function1 f1;
  private int               ascending;
  public OrderBy(Function1 f1)
  {
    this(Order.Ascending, f1);
  }
  public OrderBy(Order order, Function1 f1)
  {
    this.f1 = f1;
    this.ascending = order == Order.Ascending ? 1 : -1;
  }
  public static > OrderBy ascending(Function1 f1)
  {
    return new OrderBy<>(Order.Ascending, f1);
  }
  public static > OrderBy descending(Function1 f1)
  {
    return new OrderBy<>(Order.Descending, f1);
  }
  @Override
  public int compare(T a, T b)
  {
    Comparable v1 = (Comparable) f1.call(a);
    Out v2 = f1.call(b);
    if (v1 == null || v2 == null)
    { return compareNull(v1, v2); }
    return v1.compareTo((Object) v2) * ascending;
  }
  public static int compareNull(Object o1, Object o2)
  {
    if (o1 == o2)
    { return 0; }
    return (o1 == null) ? -1 : 1;
  }
}