Last active
March 25, 2019 14:57
-
-
Save alfonsomunozpomer/d04a8ffc1237423c448308d667a66768 to your computer and use it in GitHub Desktop.
Comparator of strings that sorts them in any arbitrary order, giving precedence to prescribed stings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ArbitraryStringComparator implements Comparator<String> { | |
private final ImmutableList<String> stringsInOrder; | |
private ArbitraryStringComparator(String... stringsInOrder) { | |
this.stringsInOrder = ImmutableList.copyOf(stringsInOrder); | |
} | |
@Override | |
public int compare(String o1, String o2) { | |
if (stringsInOrder.contains(o1) && stringsInOrder.contains(o2)) { | |
return stringsInOrder.indexOf(o1) - stringsInOrder.indexOf(o2); | |
} | |
if (stringsInOrder.contains(o1)) { // && !stringsInOrder.contains(o2) | |
return -1; | |
} | |
if (stringsInOrder.contains(o2)) { // && !stringsInOrder.contains(o1) | |
return 1; | |
} | |
return o1.compareTo(o2); // !stringsInOrder.contains(o1) && !stringsInOrder.contains(o2) | |
} | |
} | |
private static Comparator<String> getArbitraryStringComparator(String... stringsInOrder) { | |
// The list and the comparator are both reversed to get the argument strings first, and then the other elements | |
Comparator<String> arbitraryComparator = | |
comparing(s -> ImmutableList.copyOf(stringsInOrder).reverse().indexOf(s)); | |
return arbitraryComparator.reversed().thenComparing(naturalOrder()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment