gpt4 book ai didi

java - 在 int 属性上按降序对自定义对象数组进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:41:01 24 4
gpt4 key购买 nike

我想按出生年份降序排列我的数组。我的数组还有两个其他类型的 String 元素。因此,例如,出生在最早年份(例如 1939 年)的人将排在首位,然后依此类推。

这是我的代码:

import java.util.*;
public class StudentInformationTest
{
public static void main (String [] args){
StudentInformation[] studentInfo = new StudentInformation[10];

studentInfo[0] = new StudentInformation("Student A",1971, "BSc FDIT");
studentInfo[1] = new StudentInformation("Student B",1964, "BSc FDIT");
studentInfo[2] = new StudentInformation("Student C",1996, "BSc FDIT");
studentInfo[3] = new StudentInformation("Student D",1939, "BSc FDIT");
studentInfo[4] = new StudentInformation("Student E",1945, "BSc FDIT");
studentInfo[5] = new StudentInformation("Student F",1991, "BSc FDIT");
studentInfo[6] = new StudentInformation("Student G",1987, "BSc FDIT");
studentInfo[7] = new StudentInformation("Student H",1968, "BSc FDIT");
studentInfo[8] = new StudentInformation("Student I",1968, "BSc FDIT");
studentInfo[9] = new StudentInformation("Student J",1973, "BSc FDIT");

printInfo(studentInfo);
printAge(studentInfo);
}
public static void printInfo(StudentInformation studentInfo[]){
for(int i = 0; i < studentInfo.length; i++){
System.out.println(studentInfo[i].getStudentName() + " " + studentInfo[i].getBirthDate() + " " + studentInfo[i].getProgrammeOfStudy());
}
System.out.println();
}

}

}

一旦我设法按降序打印出生年份,我还需要显示学生姓名和他们正在学习的大学模块。我知道其他问题已被问到如何执行此操作,但我无法看到其他对象。这是一个类,所以请原谅我的代码中的任何错误。

最佳答案

使用 Comparator和一个 ArrayList .

在 Java 8 中

Comparator 上使用新的默认和静态方法!

ArrayList<StudentInformation> infos = new ArrayList<StudentInformation>();
// fill array
Collections.sort(infos,
Comparator.comparingInt(StudentInformation::getBirthYear).reversed());

这是一个勇敢的新世界! :)

或者——仍然比 Java 7 更好——使用 lambdas !

ArrayList<StudentInformation> infos = new ArrayList<StudentInformation>();
// fill array
Collections.sort(infos, (s1, s2) ->
Integer.compare(s2.getBirthYear(), s1.getBirthYear()));

在 Java 7 中

使用匿名内部类。

class StudentDateComparator implements Comparator<StudentInformation> {
public int compare(StudentInformation s1, StudentInformation s2) {
return Integer.compare(s2.getBirthYear(), s1.getBirthYear());
}
}

ArrayList<StudentInformation> infos = new ArrayList<StudentInformation>();
// fill array
Collections.sort(infos, new StudentDateComparator());

解释

什么 Comparator做的是允许任何东西比较给定类型的两个对象(在本例中为 StudentInformation )。你也可以制作 StudentInformation实现 Comparable<StudentInformation> , 但这种方法可能更好,因为有不止一种方法可以比较学生信息(按日期,如此处,但也可以按名字、姓氏、注册类(class)数等)。

通过交换 s1 的顺序和 s2在比较器中,我们引入了相反的顺序。另一种方法是否定 compare按正常顺序调用,或使用普通比较器并将其包装在 Collections.reverseOrder 中.


您也可以使用标准数组执行此操作。

StudentInformation[] infos = new StudentInformation[10];
// fill array
Arrays.sort(infos, new StudentDateComparator());

关于java - 在 int 属性上按降序对自定义对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15326248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com