码迷,mamicode.com
首页 > 编程语言 > 详细

Java Collections.sort方法对list集合排序

时间:2016-10-20 23:53:52      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

1、排序测试类

技术分享
package com.ljq.test;

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

public class UserSort {

    public static void main(String[] args) {
        List<User> userList =new ArrayList<User>();
        userList.add(new User(1,2.2));
        userList.add(new User(2,1.1));
        userList.add(new User(3,4.4));
        userList.add(new User(4,5.5));
        userList.add(new User(5,3.3));
        
        Collections.sort(userList, new Comparator<User>() {
            public int compare(User u1, User u2) {
                return new Double(u1.getSalary()).compareTo(new Double(u2.getSalary())); //升序
                // return new Double(u2.getSalary()).compareTo(new Double(u2.getSalary())); //降序
            }
        });
        
        for(User user : userList){
            System.out.println(user);
        }
    }
}
技术分享

 

2、User对象,存储javabean属性

技术分享
package com.ljq.test;

import java.io.Serializable;

/**
 * 用户
 *
 * @author jqlin
 */
public class User implements Serializable{
    private static final long serialVersionUID = 1L;
    
    private long id; // 主键
    private double salary; // 薪资

    public User() {

    }

    public User(long id, double salary) {
        super();
        this.id = id;
        this.salary = salary;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", salary=" + salary + "]";
    }

}
技术分享

Java Collections.sort方法对list集合排序

标签:

原文地址:http://www.cnblogs.com/xalde/p/5982650.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!