目标:实现对Person 对象的年龄,从小到大排序
1、实现排序
1 package com.app; 2 3 import java.util.ArrayList; 4 import java.util.Collections; 5 import java.util.Comparator; 6 import java.util.List; 7 8 public class A1 { 9 10 public static void main(String[] args) { 11 List<Person> list = getData() ; 12 //排序 13 Collections.sort( list , comparator ); 14 15 for (Person person : list) { 16 System.out.println("person " + person.getName() + " " + person.getAge() ); 17 } 18 19 } 20 21 /** 22 * 年龄按从小到大排序 23 */ 24 static Comparator<Person> comparator = new Comparator<Person>() { 25 @Override 26 public int compare(Person p1 , Person p2 ) { 27 if( p1.getAge() > p2.getAge() ){ 28 return 1 ; //正数 29 }else if ( p1.getAge() < p2.getAge()) { 30 return -1 ; //负数 31 }else { 32 return 0; //相等为0 33 } 34 } 35 }; 36 37 static private List<Person> getData() { 38 List<Person> list = new ArrayList<>() ; 39 40 Person p1 = new Person() ; 41 p1.setAge( 10 ); 42 p1.setName( "p1" ); 43 44 Person p2 = new Person() ; 45 p2.setAge( 30 ); 46 p2.setName( "p2" ); 47 48 Person p3 = new Person() ; 49 p3.setAge( 20 ); 50 p3.setName( "p3" ); 51 52 Person p4 = new Person() ; 53 p4.setAge( 15 ); 54 p4.setName( "p4" ); 55 56 list.add( p1 ) ; 57 list.add( p2 ) ; 58 list.add( p3 ) ; 59 list.add( p4 ) ; 60 61 return list ; 62 } 63 }
2、创建Person类
package com.app; public class Person { private int age ; private String name ; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3、运行结果(实现对年龄的排序)
person p1 10
person p4 15
person p3 20
person p2 30
时间: 2024-09-28 19:03:53