给对象排序
package jihe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* 测试list
* xutengteng
* 2017-9-19
*/
public class ListTest {
public static void main(String[] args) {
listSort();
}
/**测试list排序*/
public static void listSort(){
Student stu1 = new Student();
stu1.setAge(18);
Student stu2 = new Student();
stu2.setAge(11);
Student stu3 = new Student();
stu3.setAge(15);
Student stu4 = new Student();
stu4.setAge(12);
List<Student> stuList = new ArrayList<Student>();
stuList.add(stu1);
stuList.add(stu2);
stuList.add(stu3);
stuList.add(stu4);
Collections.sort(stuList, new ListComparator());
System.out.println("===========降序排列==========");
for (int i = 0; i < stuList.size(); i++) {
System.out.println(stuList.get(i).getAge()); //降序排列
}
Collections.sort(stuList, new ListComparators());
System.out.println("===========升序排列==========");
for (int i = 0; i < stuList.size(); i++) {
System.out.println(stuList.get(i).getAge()); //升序排列
}
}
}
class Student{
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class ListComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
//降序排列
if(o2.getAge()>o1.getAge()){
return 1;
}
if(o2.getAge()<o1.getAge()){
return -1;
}
return 0;
}
}
class ListComparators implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
//升序排列
if(o2.getAge()<o1.getAge()){
return 1;
}
if(o2.getAge()>o1.getAge()){
return -1;
}
return 0;
}
}
打印的结果
===========降序排列==========
18
15
12
11
===========升序排列==========
11
12
15
18