JAVA 使用Comparator接口实现自定义排序
1、原则
Comparator接口可以实现自定义排序,实现Comparator接口时,要重写compare方法:
int compare(Object o1, Object o2) 返回一个基本类型的整型
如果要按照升序排序,则o1 小于o2,返回-1(负数),相等返回0,01大于02返回1(正数)
如果要按照降序排序,则o1 小于o2,返回1(正数),相等返回0,01大于02返回-1(负数)
1 import java.util.ArrayList; 2 import java.util.Comparator; 3 import java.util.List; 4 5 public class UserComparator implements Comparator < User > { 6 7 public static void main( String[] args ) { 8 List < User > users = new ArrayList < User >(); 9 users.add( new User( 10, "a" ) ); 10 users.add( new User( 11, "d" ) ); 11 users.add( new User( 15, "s" ) ); 12 users.add( new User( 6, "x" ) ); 13 users.add( new User( 17, "a" ) ); 14 users.add( new User( 17, "b" ) ); 15 users.add( new User( 17, "c" ) ); 16 users.add( new User( 17, "d" ) ); 17 UserComparator comparator = new UserComparator(); 18 19 users.sort( comparator ); 20 // 也可以使用:Collections.sort( users, comparator ); 21 22 for ( User u : users ) { 23 System.out.println( u ); 24 } 25 } 26 27 @Override 28 public int compare( User u1, User u2 ) { 29 if ( u1.equals( u2 ) ) { 30 return 0; 31 } 32 else if ( u1.getAge() < u2.getAge() ) { 33 return 1; 34 } 35 else if ( u1.getAge() == u2.getAge() ) { 36 int f = u1.getName().compareTo( u2.getName() ); 37 if ( f < 0 ) { 38 return -1; 39 } 40 return 0; 41 } 42 else { 43 return -1; 44 } 45 } 46 } 47 48 class User { 49 private int age; 50 private String name; 51 52 public User() { 53 54 } 55 56 public User( int age, String name ) { 57 this.age = age; 58 this.name = name; 59 } 60 61 public int getAge() { 62 return age; 63 } 64 65 public void setAge( int age ) { 66 this.age = age; 67 } 68 69 public String getName() { 70 return name; 71 } 72 73 public void setName( String name ) { 74 this.name = name; 75 } 76 77 @Override 78 public String toString() { 79 return "User [age=" + age + ", name=" + name + "]"; 80 } 81 82 }
User [age=17, name=a] User [age=17, name=b] User [age=17, name=c] User [age=17, name=d] User [age=15, name=s] User [age=11, name=d] User [age=10, name=a] User [age=6, name=x]
面向对象面向君,不负代码不负卿!