Java排序 - 首先是大写的

时间:2016-06-02 05:38:31

标签: java arrays collections comparator comparable

我想对这些项目进行排序(所有大写首先排序):

A
B
C
D
a
b
c
d

如何使用集合排序?假设我的对象是Account,accountName是我想要按那种方式排序的字段

感谢

2 个答案:

答案 0 :(得分:2)

您需要在帐户类中实现Comparable接口并覆盖compareTo()方法。

class Account implements Comparable{

    public String accountName;

    public Account(String accountName) {
        this.accountName = accountName;
    }

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    @Override
    public String toString() {
        return "Account [accountName=" + accountName + "]";
    }

    @Override
    public int compareTo(Object obj) {
        Account accObj = (Account) obj;

        return this.accountName.compareTo(accObj.accountName);
    }

}

现在Collections.sort()将返回您想要的结果。

List<Account> accList= new ArrayList<Account>();
accList.add(new Account("B"));
accList.add(new Account("c"));
accList.add(new Account("A"));

accList.add(new Account("C"));
accList.add(new Account("a"));
accList.add(new Account("b"));

Collections.sort(accList);

答案 1 :(得分:0)

您是否正在尝试寻找解决方案? 您始终可以编写自定义Comparator或使用现有的

//List<Account> accounts = new ArrayList<>();
Set<Account> sorted = accounts.stream().sorted(((o1, o2) -> o1.getName().compareTo(o2.getName()))).collect(Collectors.toSet());

Set<Account> sorted = accounts.stream().sorted(((o1, o2) -> {
   //do whatever you want with your custom comparator logic
})).collect(Collectors.toList());