StartsWithComparator.java

  1. package no.nav.data.common.utils;

  2. import org.apache.commons.lang3.StringUtils;

  3. import java.util.Comparator;

  4. import static java.lang.String.CASE_INSENSITIVE_ORDER;

  5. /**
  6.  * String comparator that first sorts strings that start with a given prefix, then alphabetically
  7.  */
  8. public class StartsWithComparator implements Comparator<String> {

  9.     private final String prefix;

  10.     public static Comparator<String> startsWith(String prefix) {
  11.         return new StartsWithComparator(prefix).thenComparing(CASE_INSENSITIVE_ORDER);
  12.     }

  13.     private StartsWithComparator(String prefix) {
  14.         this.prefix = prefix;
  15.     }

  16.     @Override
  17.     public int compare(String o1, String o2) {
  18.         return start(o1) - start(o2);
  19.     }

  20.     private int start(String string) {
  21.         int start = StringUtils.indexOfIgnoreCase(string, prefix);
  22.         return start < 0 ? Integer.MAX_VALUE : start;
  23.     }
  24. }