我想按出生年份的降序对我的数组进行排序。
我的数组还有两个其他类型为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();
}
}
}
一旦我按降序打印出生年份,我还需要显示学生姓名和他们正在从事的大学类(class)。
我知道有人问过其他问题怎么做,但我看不到其他物体。
这是一次类 session ,因此请原谅我的代码中的任何错误。
最佳答案
使用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/