我有一个List,我想使用spring表达式排序。我目前正在使用Comparator和TreeSet,比较器采用spring表达式并比较解析列表中每个成员的spring表达式的结果。
它可能有用(我还没有测试过),我一直想知道是否有人知道更好的方法。
这就是我目前对比较器的看法。 :
public class SpringElComparator implements Comparator<Object> {
private static ExpressionParser parser = new SpelExpressionParser();
private static Map<String, Expression> expCache = new HashMap<>();
private Expression exp;
public SpringELRule(String expression) {
exp = expCache.get(expression);
if(exp == null) {
exp = new Expression(expression);
expCache.put(expression, exp);
}
}
@Override
public int compare(Object o1, Object o2) {
Object c1 = exp.getValue(o1);
Object c2 = exp.getValue(o2);
int result;
if (c1 instanceof Comparator) {
Comparator comparator1 = (Comparator)c1;
Comparator comparator2 = (Comparator)c2;
result = comparator1.compare(comparator2);
} else if (c1 instanceof Comparable) {
Comparable comparable1 = (Comparable)c1;
Comparable comparable2 = (Comparable)c2;
result = comparable1.compareTo(comparable2);
}
if(result == 0) {
return -1;
} else {
return result;
}
}
}