本文介绍了如何按私有字段对列表排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的实体类如下:
public class Student {
private int grade;
// other fields and methods
}
我这样使用它:
List<Student> students = ...;
考虑到这是一个私有字段,如何将students
按grade
排序?
How can I sort students
by grade
, taking into account that it is a private field?
推荐答案
您有以下选择:
- 使
grade
可见 - 定义
grade
的吸气方法 - 在内部定义
Comparator
Student
- 使
Student
实现Comparable
- (我认为这不是解决方案,它是解决方法/ hack )
- make
grade
visible - define a getter method for
grade
- define a
Comparator
insideStudent
- make
Student
implementComparable
- (in my opinion this is not a solution, it is a workaround/hack)
解决方案3
的示例:
Example for solution 3
:
public class Student {
private int grade;
public static Comparator<Student> byGrade = Comparator.comparing(s -> s.grade);
}
并像这样使用它:
List<Student> students = Arrays.asList(student2, student3, student1);
students.sort(Student.byGrade);
System.out.println(students);
这是我最喜欢的解决方案,因为:
This is my favorite solution because:
- 您可以轻松定义几个
Comparator
- 代码不多
- 您的字段保持私有和封闭状态
解决方案4
的示例:
public class Student implements Comparable {
private int grade;
@Override
public int compareTo(Object other) {
if (other instanceof Student) {
return Integer.compare(this.grade, ((Student) other).grade);
}
return -1;
}
}
您可以像这样在任何地方进行排序:
You can sort everywhere like this:
List<Student> students = Arrays.asList(student2, student3, student1);
Collections.sort(students);
System.out.println(students);
此解决方案的方面:
- This defines, that sorting by
grade
represents the natural order of students - Some preexisting methods will automatically sort (like
TreeMap
)
这篇关于如何按私有字段对列表排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!