【问题标题】:Best way to combine multiple sorts in API 21在 API 21 中组合多种排序的最佳方式
【发布时间】:2018-07-24 22:10:45
【问题描述】:

我的目标是对由字符串和布尔值组成的对象列表应用 2 种排序。

我有帐户和活动/非活动状态,所以我想首先显示活动(对布尔值排序),然后按字母顺序对其余元素进行排序。

例如:

[约翰,不活跃],[克雷格,活跃],[迈克,不活跃],[丹尼斯,不活跃]

我想拥有:

[Craig,active], [Dennis,innactive], [John,inactive], [Mike,inactive]

我打算做的是使用 Comparable 但我想知道是否有其他方法可以做到这一点。

我不想使用 Guava 或任何其他库。 这也应该用于 Android API 21,因此不能使用 list.sort()。

提前致谢!

【问题讨论】:

    标签: java android sorting


    【解决方案1】:

    像这样简单地创建一个新的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));
    

    【讨论】:

    • 这是最好的答案,+1
    • 它工作正常。我已经以这种方式做到了,这似乎是唯一的解决方案。谢谢,接受:)
    【解决方案2】:

    如果没有 Java 8 或一些第三方库,就没有神奇/简单的方法可以做到这一点。您必须实施 Comparable 并自己完成繁重的工作:

    public class Person implements Comparable<Person> {
    
        private final boolean isActive;
        private final String name;
    
        @Override
        public int compareTo(Person other) {
            if (isActive && !other.isActive) {
                return -1;
            } else if (!isActive && other.isActive) {
                return 1;
            } else {
                return name.compareTo(other.name);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      相关资源
      最近更新 更多