ArrayList集合储存对象并排序(Java)
存储一个学生类并输出(年龄相同时比较姓名):
Student:
public class Student {
private int ege;
private String name;
public Student(int ege, String name) {
this.ege = ege;
this.name = name;
}
public int getEge() {
return ege;
}
public void setEge(int ege) {
this.ege = ege;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
StudentDemo:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class StudentDemo {
public static void main(String[] args) {
ArrayList<Student> arrayList = new ArrayList<>();
Student a = new Student(11,"诸葛亮");
Student b = new Student(12,"刘备");
Student c = new Student(18,"孙权");
Student d = new Student(13,"孙策");
arrayList.add(a);
arrayList.add(b);
arrayList.add(c);
arrayList.add(d);
Collections.sort(arrayList, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num = o1.getEge() - o2.getEge();
int num1=num==0?o1.getName().compareTo(o2.getName()):num;
return num1;
}
});
for (Student s:arrayList
) {
System.out.println("年龄"+s.getEge()+" , "+"姓名"+s.getName());
}
}
}