Java 如何在两个不同的字段上使用Collections.sort()?

Java 如何在两个不同的字段上使用Collections.sort()?,java,sorting,arraylist,collections,Java,Sorting,Arraylist,Collections,我有一个成员类,如下所示: public class Member { private int value1; private boolean value2; } 以及包含以下数据的ArrayList: 值1-值2 1-错误 2-错误 3-正确 4-错误 5-正确 现在我希望这些数据按如下方式排序: 必须首先返回value2为true的成员,然后返回后面的其他成员 在每个子列表中,成员将从最高值返回到最低值value1 因此,最后,列表应该按以下顺序包含数据:5、3、4

我有一个
成员
类,如下所示:

public class Member {
    private int value1;
    private boolean value2;
}
以及包含以下数据的
ArrayList

值1-值2

  • 1-错误
  • 2-错误
  • 3-正确
  • 4-错误
  • 5-正确
现在我希望这些数据按如下方式排序:

  • 必须首先返回
    value2
    为true的成员,然后返回后面的其他成员
  • 在每个子列表中,成员将从最高值返回到最低值
    value1
因此,最后,列表应该按以下顺序包含数据:5、3、4、2、1

我知道我可以使用
Collections.sort()
按值1对数据进行排序:

Collections.sort(memberList, new Comparator<Member>(){
    public int compare(Member m1, Member m2){
        return m1.getValue1() - m2.getValue1();
    }
});
Collections.sort(memberList,newcomparator(){
公共整数比较(成员m1、成员m2){
返回m1.getValue1()-m2.getValue1();
}
});
但是有没有一种方法可以在同一个
比较
方法中按两个标准对数据进行排序


谢谢您的帮助。

您可以先通过
value2
进行比较,如果是平局,则通过
value1
进行比较:

Collections.sort(memberList, new Comparator<Member>(){
    public int compare(Member m1, Member m2){
        int comp = Boolean.compare(m1.getValue2(), m2.getValue2());

        if (comp == 0) {
            // case where 'value2' is the same for both inputs
            // in this case use 'value1' to compare
            comp = m1.getValue1() - m2.getValue1();
        }
        return comp;
    }
});
Collections.sort(memberList,newcomparator(){
公共整数比较(成员m1、成员m2){
int comp=Boolean.compare(m1.getValue2(),m2.getValue2());
如果(comp==0){
//两个输入的“value2”相同的情况
//在这种情况下,使用“value1”进行比较
comp=m1.getValue1()-m2.getValue1();
}
返回补偿;
}
});

您可以先通过
value2
进行比较,如果是平局,则通过
value1
进行比较:

Collections.sort(memberList, new Comparator<Member>(){
    public int compare(Member m1, Member m2){
        int comp = Boolean.compare(m1.getValue2(), m2.getValue2());

        if (comp == 0) {
            // case where 'value2' is the same for both inputs
            // in this case use 'value1' to compare
            comp = m1.getValue1() - m2.getValue1();
        }
        return comp;
    }
});
Collections.sort(memberList,newcomparator(){
公共整数比较(成员m1、成员m2){
int comp=Boolean.compare(m1.getValue2(),m2.getValue2());
如果(comp==0){
//两个输入的“value2”相同的情况
//在这种情况下,使用“value1”进行比较
comp=m1.getValue1()-m2.getValue1();
}
返回补偿;
}
});

compare中的代码都是您的。您可以比较m1.getVaue2()和m2.getValue2()…这不像您可以在方法compare中只写一行…天哪@Rob在你问代码之前先学会比较里面的代码都是你的。您可以比较m1.getVaue2()和m2.getValue2()…这不像您可以在方法compare中只写一行…天哪@罗布,在你开口之前先学会说话
Collections.sort(memberList, 
       Comparator.comparing(Member::getValue2).thenComparing(Member::getValue1).reversed());