以(区分大小写)字母顺序对字符串进行排序的简单方法 [英] Simple way to sort strings in the (case sensitive) alphabetical order

查看:220
本文介绍了以(区分大小写)字母顺序对字符串进行排序的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要按字母顺序对字符串列表进行排序:

I need to sort list of strings in the alphabetical order:

List<String> list = new ArrayList();
list.add("development");
list.add("Development");
list.add("aa");
list.add("AA");
list.add("Aa");

常用的方法是使用比较器:

A common way to do it is to use comparator:

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

CaseInsensitiveComparator的问题是AA等于aa。字符串会根据相同值的添加顺序显示在结果中,并且不正确:

The problem of the CaseInsensitiveComparator that "AA" is equals to "aa". Strings appear in the result according to the order of adding for the same values, and it is not correct:

"aa","AA","Aa","development","Development"


推荐答案

如果您不想在Guava上添加依赖项(根据Michael的回答),那么这个比较器是等价的:

If you don't want to add a dependency on Guava (per Michael's answer) then this comparator is equivalent:

private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
    public int compare(String str1, String str2) {
        int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
        if (res == 0) {
            res = str1.compareTo(str2);
        }
        return res;
    }
};

Collections.sort(list, ALPHABETICAL_ORDER);

我认为这很容易理解和编码......

And I think it is just as easy to understand and code ...

该方法的最后4行可以更简洁地写成如下:

The last 4 lines of the method can written more concisely as follows:

        return (res != 0) ? res : str1.compareTo(str2);

这篇关于以(区分大小写)字母顺序对字符串进行排序的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆