首页 > 代码库 > 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集合排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。