List集合自定义排序
利用集合自带工具类排序
@Test
public void test18 ( ) {
List< DataRow> result = new ArrayList < DataRow> ( ) ;
for ( int i= 0 ; i< 10 ; i++ )
{
DataRow d = new DataRow ( ) ;
d. set ( "sort" , ( int ) ( Math. random ( ) * 10 ) + "" ) ;
result. add ( d) ;
}
Collections. sort ( result, new Comparator < DataRow> ( ) {
@Override
public int compare ( DataRow d1, DataRow d2) {
int sort1 = d1. getInt ( "sort" ) ;
int sort2 = d2. getInt ( "sort" ) ;
return sort1- sort2;
}
} ) ;
for ( DataRow dataRow : result)
{
System. out. println ( dataRow. getString ( "sort" ) ) ;
}
}
实现Comparable接口,重写compareTo方法实现排序
public class Person implements Comparable < Person> {
private String name;
private int age;
public Person ( String name, int age) {
super ( ) ;
this . name = name;
this . age = 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;
}
@Override
public int compareTo ( Person o) {
if ( this . age > o. getAge ( ) ) {
return 1 ;
}
if ( this . age < o. getAge ( ) ) {
return - 1 ;
}
return 0 ;
}
}
public static void main ( String[ ] args) {
List< Person> list = new ArrayList < Person> ( ) ;
list. add ( new Person ( "麻刘" , 2 ) ) ;
list. add ( new Person ( "张三" , 30 ) ) ;
list. add ( new Person ( "李四" , 20 ) ) ;
list. add ( new Person ( "王五" , 10 ) ) ;
list. add ( new Person ( "小红" , 5 ) ) ;
for ( Person person : list)
{
System. out. println ( person. toString ( ) ) ;
}
System. out. println ( "--------------------------------" ) ;
Collections. sort ( list) ;
for ( Person person : list)
{
System. out. println ( person. toString ( ) ) ;
}
}