我想根据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
答案 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);
});