像这样简单地创建一个新的Comparator:
public class AccountComparator implements Comparator<Account> {
@Override
public int compare(Account o1, Account o2) {
if (o1.isActive() && !o2.isActive()) {
return -1;
}
if (!o1.isActive() && o2.isActive()) {
return 1;
}
return o1.getName().compareTo(o2.getName());
}
}
最小测试示例:
public static void main(String[] args) {
Account account2 = new Account("B", true);
Account account4 = new Account("D", false);
Account account3 = new Account("C", true);
Account account1 = new Account("A", false);
List<Account> list = new ArrayList<>();
list.add(account1);
list.add(account2);
list.add(account3);
list.add(account4);
Collections.sort(list, new AccountComparator());
list.forEach(System.out::println);
}
预期输出为
Account{name='B', active=true}
Account{name='C', active=true}
Account{name='A', active=false}
Account{name='D', active=false}
或者使用 lambda 表达式:(感谢 @Wow 使用 Comparator.comparing)
Collections.sort(list, Comparator.comparing(Account::isActive).reversed()
.thenComparing(Account::getName));