list排序

来源:互联网 发布:matlab 图像配准算法 编辑:程序博客网 时间:2024/06/13 09:29

list里面是Student对象,根据Student对象的age值进行升序和降序排序


package test;public class Student {private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}



package test;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class MyTest1 {public static void main(String[] args) {Student s1 = new Student();Student s2 = new Student();Student s3 = new Student();Student s4 = new Student();Student s5 = new Student();s1.setName("丑哥最风骚21");s1.setAge(21);s2.setName("丑哥最风骚22");s2.setAge(22);s3.setName("丑哥最风骚25");s3.setAge(25);s4.setName("丑哥最风骚23");s4.setAge(23);s5.setName("丑哥最风骚24");s5.setAge(24);List<Student> list = new ArrayList<Student>();list.add(s1);list.add(s2);list.add(s3);list.add(s4);list.add(s5);Collections.sort(list, new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {int age1 = o1.getAge();int age2 = o2.getAge();//if(age1 < age2) {// 降序if(age1 > age2) {// 升序return 1;} else if(age1 == age2) {return 0;} else {return -1;}}});for(Student s : list) {System.out.println(s.getAge());}}}


0 0
原创粉丝点击