package com.bootdo.common.config.collection.vo; /** * @ClassName : Student * @Description: 第一种是实体类实现Comparable<Student> ,重写compareTo的方法 * @Author: 13394 * @CreateDate: 2018/10/18 12:41 * @Version: 1.0 */ public class Student implements Comparable<Student>{ private String name; private Integer age; public Student(String name,Integer age) { this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public int compareTo(Student o) { if(this.age>o.getAge()){ return 1; } else if(this.age<o.getAge()){ return -1; } else{ return 0; } } }
//测试的方法 @Test public void test34(){ List<Student> list=new ArrayList<Student>(); Student s1=new Student("T-F", 18); Student s2=new Student("H胡歌", 28); Student s3=new Student("Z周润发", 50); Student s4=new Student("M梅兰芳", 100); list.add(s1); list.add(s4); list.add(s3); list.add(s2); System.out.println("------默认排序(按年纪)-------"); Collections.sort(list); for (int i = 0; i < list.size(); i++) { Student student = list.get(i); System.out.println(student.getAge()+","+student.getName()); } Collections.sort(list,Collections.reverseOrder()); for (int i = 0; i < list.size(); i++) { Student student = list.get(i); System.out.println(student.getAge()+","+student.getName()); } }
//第二种的实现方法 @Test public void test33() { List<Student> list = new ArrayList<Student>(); Student s1 = new Student("T-F", 18); Student s2 = new Student("H胡歌", 28); Student s3 = new Student("Z周润发", 50); Student s4 = new Student("M梅兰芳", 100); list.add(s1); list.add(s4); list.add(s3); list.add(s2); Collections.sort(list, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { if(o1.getAge()>o2.getAge()){ return 1; } else if(o1.getAge()<o2.getAge()){ return -1; } else{ return 0; } } }); for (int i = 0; i < list.size(); i++) { Student student = list.get(i); System.out.println(student.getAge() + "," + student.getName()); } }