首页 > 代码库 > Java Collections.sort方法对list集合排序

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

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集合排序