使用Java在同一程序中的升序和降序

时间:2018-12-05 10:09:55

标签: java list sorting arraylist collections

我想根据ID和标记对对数据进行排序。 ID应该按升序排列,标记应该按降序排列,这是我的代码:

ArrayList<Student> al=new ArrayList<Student>();
    al.add(new Student(1,"dg",58));
    al.add(new Student(2,"dg",48));
    al.add(new Student(1,"dg",98));
    al.add(new Student(2,"dg",68));
    al.add(new Student(1,"dg",38));
    al.add(new Student(2,"dg",28));
    al.add(new Student(2,"dg",90));    

输出类似:

1 dg 98  
1 dg 58  
1 dg 38  
2 dg 90  
2 dg 68  
2 dg 48  
2 dg 28  

2 个答案:

答案 0 :(得分:7)

您必须为Student类实现Comparable或使用自定义Comparator直接对其进行排序:

Comparator<Student> comparator = Comparator
    .comparing(Student::getId)                            // First ID in ascending order
    .thenComparing(Comparator.comparing(Student::getMark) // Then mark 
                             .reversed());                // ... but in descending order

al.sort(comparator);                                      // Here is the sort performed

答案 1 :(得分:2)

尝试

 Collections.sort(al,(s1,s2)->{

            return s1.id<s2.id?-1:s1.id>s2.id?1:s1.marks>s2.marks?-1:0;
        });
        al.forEach(p->{
            System.out.println(p);
        });