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

net.sf.javagimmicks.util.CompositeComparator Maven / Gradle / Ivy

There is a newer version: 0.99-alpha1
Show newest version
package net.sf.javagimmicks.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * A {@link Comparator} implementation that wraps a list of delegate
 * {@link Comparator}s and applies them in the given order when comparing
 * objects.
 * 
 * @param 
 *           the type of objects to compare
 */
public class CompositeComparator implements Comparator
{
   private final List> _comparators;

   /**
    * Creates a new instance for the given delegate {@link Comparator}s
    * 
    * @param comparators
    *           the delegate {@link Comparator}s to use internally
    */
   public CompositeComparator(final List> comparators)
   {
      _comparators = new ArrayList>(comparators);
   }

   /**
    * Creates a new instance for the given delegate {@link Comparator}s
    * 
    * @param comparators
    *           the delegate {@link Comparator}s to use internally
    */
   public CompositeComparator(@SuppressWarnings("unchecked") final Comparator... comparators)
   {
      this(Arrays.asList(comparators));
   }

   @Override
   public int compare(final E o1, final E o2)
   {
      for (final Comparator comparator : _comparators)
      {
         final int compareResult = comparator.compare(o1, o2);

         if (compareResult != 0)
         {
            return compareResult;
         }
      }

      return 0;
   }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy