Java Collections.sort方法对list集合排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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集合排序的主要内容,如果未能解决你的问题,请参考以下文章
java list排序的两种方式(实现Comparable接口和Collections.sort重载方法)
Java语言利用Collections.sort对Map,List排序
Java里面的Collections.sort(list)。 sort这个方法在API哪里能找的到