Last active
May 6, 2017 08:22
-
-
Save martin-tarjanyi/7637cbdade234889d9ec7e394462ebe6 to your computer and use it in GitHub Desktop.
Explicit comparator based on guava explicit ordering
This file contains 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
import java.util.Comparator; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
@ToString | |
@EqualsAndHashCode | |
public final class ExplicitComparator<T> implements Comparator<T> | |
{ | |
private final Map<T, Integer> rankMap; | |
private ExplicitComparator(List<T> valuesInOrder) | |
{ | |
this.rankMap = buildRankMap(valuesInOrder); | |
} | |
public static <T> ExplicitComparator<T> of(List<T> valuesInOrder) | |
{ | |
return new ExplicitComparator<>(valuesInOrder); | |
} | |
private static <T> Map<T, Integer> buildRankMap(List<T> valuesInOrder) | |
{ | |
Map<T, Integer> map = new HashMap<>(); | |
int rank = 0; | |
for (T value : valuesInOrder) | |
{ | |
map.put(value, rank++); | |
} | |
return map; | |
} | |
@Override | |
public int compare(T left, T right) | |
{ | |
return rank(left) - rank(right); | |
} | |
private int rank(T value) | |
{ | |
Integer rank = rankMap.get(value); | |
if (rank == null) | |
{ | |
return rankMap.size(); | |
} | |
return rank; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment