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 + "]"; } }
3、多字段排序,基本数字类型要用封装数字类型才可以排序,如:new Double()
Collections.sort(dataList, new Comparator<OrderVO>(){ public int compare(OrderVO a, OrderVO b) { //先按期号降序,如果期号相同按玩法名称降序,如果玩法名称相同按投注时间降序 int result = b.getCreateTime().compareTo(a.getCreateTime()); if(result == Zero.INT){ return new Integer(a.getSort()).compareTo(new Integer(b.getSort())); }else{ return result; } } });