cdc.issues.demos.WeightComparator Maven / Gradle / Ivy
package cdc.issues.demos;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A String Comparator based on a specific order.
*
* TODO remove when cdc-util released.
*
* @author Damien Carbonne
*/
class WeightComparator implements Comparator {
private final Map weights = new HashMap<>();
private final int defaultWeight;
public WeightComparator(int defaultWeight,
String... values) {
this.defaultWeight = defaultWeight;
int weight = 0;
for (final String value : values) {
weights.put(value, weight);
weight++;
}
}
public WeightComparator(int defaultWeight,
List values) {
this.defaultWeight = defaultWeight;
int weight = 0;
for (final String value : values) {
weights.put(value, weight);
weight++;
}
}
@Override
public int compare(String o1,
String o2) {
final int w1 = weights.getOrDefault(o1, defaultWeight);
final int w2 = weights.getOrDefault(o2, defaultWeight);
if (w1 == w2) {
return o1.compareTo(o2);
} else {
return w1 - w2;
}
}
}