分享

Comparator进行排序

 weixiaofeng01 2017-02-16
package Demo;

import java.util.ArrayList;  
import java.util.Collections;  
import java.util.Comparator;  
import java.util.List;  
  
//直接使用Collections来排序  
public class Client {  
  
    public static void main(String[] args) {  
//     准备要测试的数据  
        UserModel um1 = new UserModel("小明","001",21);  
        UserModel um2 = new UserModel("小王","002",24);  
        UserModel um3 = new UserModel("小李","003",25);  
        UserModel um4 = new UserModel("小吴","004",22);  
        UserModel um5 = new UserModel("小郑","005",20);  
          
        //添加到列表中  
        List<UserModel> list = new ArrayList<UserModel>();  
        list.add(um1);  
        list.add(um2);  
        list.add(um3);  
        list.add(um4);  
        list.add(um5);
        System.out.println("排序前-------------");  
        printList(list);  
          
        //实现比较器,也可以单独用一个类来实现  
        Comparator c = new Comparator(){  
  
            @Override  
            public int compare(Object arg0, Object arg1) { //这里实现按照用户年龄大小来排序  
  
            UserModel temp1 = (UserModel) arg0;  
            UserModel temp2 = (UserModel) arg1;  
              
            if(temp1.getAge()>temp2.getAge())return 1;  
            else if(temp1.getAge()<temp2.getAge())return -1;  
            else if(temp1.getAge()==temp2.getAge())return 0;  
            return 0;  
            }  
              
        };  
          
        //排序,主要就是依靠Comparator接口的具体实现  
        Collections.sort(list,c);  
          
        System.out.println("排序后-------------");  
        printList(list);  
          
    }  
  
    private static void printList(List<UserModel> list) {  
        for(UserModel um:list){  
            System.out.println(um);  
        }  
    }  
  
}

package Demo;

public class UserModel {  
 
    private String userName,userId;  
    private int age;  
    public String getUserName() {  
        return userName;  
    }  
    public String getUserId() {  
        return userId;  
    }  
    public int getAge() {  
        return age;  
    }  
    public UserModel(String userName, String userId, int age) {  
        this.userName = userName;  
        this.userId = userId;  
        this.age = age;  
    }  
      
    public String toString(){  
        return "userName="+userName+",userId="+userId+",age="+age;  
    }  
}  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多