我正在尝试编写一个方法,它将获取一个student对象的arraylist,并返回一个字符串数组,其中包含按分数顺序排列的学生姓名(分数最高的学生姓名将位于索引0处)。
public static void orderStudent(List<Student> ls) {
for (Student stu : ls) {
System.out.println("Name: " + stu.getName() + ", Score: "
+ stu.getScore());
}
}
上面的代码片段在执行时将打印如下内容
Name: Alex, Score: 10.35
Name: Bob, Score: 11.2
Name: Charles, Score: 8.22
我希望orderstudent方法返回一个字符串数组,该数组的内容[bob,alex,charles]bob是最高得分者,然后是alex和charles。
5条答案
按热度按时间bf1o4zei1#
你需要在你的计划中实现两件事
Student
班级:Comparable
,以及对.toString()
方法。首先,定义你的学生班级如下:public class Student implements Comparable<Student>
那么你必须定义.compareTo()
方法如下:同时覆盖
.toString()
方法如下:现在你可以简单地改变你的想法
orderStudents
功能如下:zhte4eai2#
首先需要对列表进行排序,然后需要构造字符串[]
你可以用
CompareToBuilder
类,而不对现有的pojo类进行任何更改。在comparetobuilder上,需要添加需要对集合进行排序的属性。您可以看到以下代码:
du7egjpx3#
如果
Student
实现Comparable
接口并按分数排序,然后您只需对列表排序,并构建名称数组。如果你不能编辑
Student
类,您需要编写一个实现Comparator<Student>
并用它来排序列表,然后构建名称数组。简化@prasadkhode的答案:
不需要创建
CompareToBuilder
每次分数比较。那太没效率了。tktrz96b4#
将数组替换为列表:
如果使用Java8,它将少于两行。。。
2mbi3lxu5#
您需要在student对象中定义一些字符串序列化(可选)
您需要使用按分数排序的自定义组件对对象进行排序(必需)
collections.sort(list,comparator c)
清单是你的清单
c是比较器
遍历已排序的集合并打印