RefComparator.java

  1. /*
  2.  * Copyright (C) 2008, Charles O'Farrell <charleso@charleso.org>
  3.  * Copyright (C) 2010, Google Inc. and others
  4.  *
  5.  * This program and the accompanying materials are made available under the
  6.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  7.  * https://www.eclipse.org/org/documents/edl-v10.php.
  8.  *
  9.  * SPDX-License-Identifier: BSD-3-Clause
  10.  */

  11. package org.eclipse.jgit.lib;

  12. import java.util.ArrayList;
  13. import java.util.Collection;
  14. import java.util.Collections;
  15. import java.util.Comparator;
  16. import java.util.List;

  17. /**
  18.  * Util for sorting (or comparing) Ref instances by name.
  19.  * <p>
  20.  * Useful for command line tools or writing out refs to file.
  21.  */
  22. public class RefComparator implements Comparator<Ref> {

  23.     /** Singleton instance of RefComparator */
  24.     public static final RefComparator INSTANCE = new RefComparator();

  25.     /** {@inheritDoc} */
  26.     @Override
  27.     public int compare(Ref o1, Ref o2) {
  28.         return compareTo(o1, o2);
  29.     }

  30.     /**
  31.      * Sorts the collection of refs, returning a new collection.
  32.      *
  33.      * @param refs
  34.      *            collection to be sorted
  35.      * @return sorted collection of refs
  36.      */
  37.     public static Collection<Ref> sort(Collection<Ref> refs) {
  38.         final List<Ref> r = new ArrayList<>(refs);
  39.         Collections.sort(r, INSTANCE);
  40.         return r;
  41.     }

  42.     /**
  43.      * Compare a reference to a name.
  44.      *
  45.      * @param o1
  46.      *            the reference instance.
  47.      * @param o2
  48.      *            the name to compare to.
  49.      * @return standard Comparator result of &lt; 0, 0, &gt; 0.
  50.      */
  51.     public static int compareTo(Ref o1, String o2) {
  52.         return o1.getName().compareTo(o2);
  53.     }

  54.     /**
  55.      * Compare two references by name.
  56.      *
  57.      * @param o1
  58.      *            the reference instance.
  59.      * @param o2
  60.      *            the other reference instance.
  61.      * @return standard Comparator result of &lt; 0, 0, &gt; 0.
  62.      */
  63.     public static int compareTo(Ref o1, Ref o2) {
  64.         return o1.getName().compareTo(o2.getName());
  65.     }
  66. }