Collections.sort() 对 List 排序

时间:2022-04-18 19:44:07

首先是List中的bean类:

class User {
    String name;
    String age;
    public User(String name,String age){
        this.name=name;
        this.age=age;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    } 
}    

然后是对应的比较类Comparator:

import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class ComparatorUser implements Comparator<User>{

    public int compare(User user0, User user1) {int flag=user0.getAge().compareTo(user1.getAge());
        if(flag == 0) {
            return user0.getName().compareTo(user1.getName());
        }else {
            return flag;
        }  
    }
}

调用此Comparator时的方法为:

    List<User> userlist=new ArrayList<User>();
    ComparatorUser comparator=new ComparatorUser();
    Collections.sort(userlist, comparator);

上面几句话执行后,userlist就会被排序了.