【问题标题】:Java/Android - Two Collections.sort combined (first by int, then by name)Java/Android - 两个 Collections.sort 组合(首先按 int,然后按名称)
【发布时间】:2014-07-22 07:04:23
【问题描述】:

我有一个包含我自己的对象的列表,称为 OrderedProducts。我想先按int sequence 排序此列表,然后按String name

我知道如何先按顺序排序,使用以下默认的 Collections.sort:

Collections.sort(orderedProductsList, new Comparator<OrderedProduct>(){
    @Override
    public int compare(OrderedProduct op1, OrderedProduct op2){
        if(op1.getSequence() < op2.getSequence())
            return -1;
        else if(op1.getSequence() > op2.getSequence())
            return 1;
        else // op1.getSequence() == op2.getSequence()
            return 0;
    }
});

我现在想要的是在有序序列中按名称排序。因此,例如,我的 List 中有以下 OrderedProducts:

  1. 序列 = 2;名称 = “AAA”;
  2. 序列 = 4;名称 = “AAA”;
  3. 序列 = 7;名称 = "BBB";
  4. 序列 = 2;名称 = "CCC";
  5. 序列 = 1;名称 = "ZZZ";
  6. 序列 = 4;名称 = "ZZZ";
  7. 序列 = 4;名称 = "ABC";

这应该是这样排序的:

5, 1, 4, 2, 7, 6, 3.

Sequence    Name

1           "ZZZ"
2           "AAA"
2           "CCC"
4           "AAA"
4           "ABC"
4           "ZZZ"
7           "BBB"

【问题讨论】:

    标签: java android list sorting arraylist


    【解决方案1】:

    在你的比较器中,当序列相等时比较名称

    Collections.sort(orderedProductsList, new Comparator<OrderedProduct>(){
        @Override
        public int compare(OrderedProduct op1, OrderedProduct op2){
            if(op1.getSequence() < op2.getSequence())
                return -1;
            else if(op1.getSequence() > op2.getSequence())
                return 1;
            else 
                return op1.getName().compareToIgnoreCase(op2.getName());            
        }
    });
    

    【讨论】:

    • 谢谢,已接受作为答案。我现在在 else 中使用 return op1.getName().compareToIgnoreCase(op2.getName());,因为名称是字符串。
    【解决方案2】:

    为此,您只需要先使用Collections.sort()按名称对集合进行排序,然后按顺序排序时,您的集合将按顺序排序,在序列内,它将按名称排序(这是因为Collections.sort() 是稳定的)。

    您可以命名您的比较方法,必须比较方法,一个用于序列,另一个用于名称,如下所示:

    取自this link

    public static Comparator < Student > NAME = new Comparator < Student > () {@
        Override
        public int compare(Student o1, Student o2) {
            return o1.name.compareTo(o2.name);
        }
    };
    public static Comparator < Student > AGE = new Comparator < Student > () {@
        Override
        public int compare(Student o1, Student o2) {
            return o1.age - o2.age;
        }
    };
    

    【讨论】:

    • 感谢您的回答,但我决定采用 FuzzyTree 的回答(在使用 Java 的默认 String#compareToIgnoreCase 方法对他的代码进行小幅更改之后)。
    猜你喜欢
    • 2017-06-23
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    相关资源
    最近更新 更多