使用BeanComparator和Collat​​or对集合进行排序

时间:2012-11-23 09:55:57

标签: java

我正在尝试使用此代码对节点列表进行排序:

private String sortPropertyName;
private void sortListUsingSortorder(List<MyNode> nodes, String sortOrder) {
        BeanComparator comparator = new BeanComparator(sortPropertyName, new Comparator() {
        public int compare(Object obj1, Object obj2) {
            if ("dsc".equals(sortOrder)) {
                return ((Comparable) obj2).compareTo(obj1);
            } else {
                return ((Comparable) obj1).compareTo(obj2);
            }
            }
        });

    Collections.sort(nodes, comparator);
    }
}

我想使用Collat​​or来实现以下排序顺序:

AaÄäBbCcUuÜü

类似这样的事情

    Collator collator = Collator.getInstance(Locale.GERMAN);
    collator.setStrength(Collator.PRIMARY);
    Collections.sort(words, collator);

如何在排序代码中使用此Collat​​or?

1 个答案:

答案 0 :(得分:1)

在比较器中委托给整理者:

BeanComparator comparator = new BeanComparator(sortPropertyName, new Comparator() {
    public int compare(Object obj1, Object obj2) {
        if ("dsc".equals(sortOrder)) {
            return collator.compare(obj2, obj1);
        } 
        else {
            return collator.compare(obj1, obj2);
        }
    }
});