Java如何实现List自定义排序
程序员文章站
2024-01-25 17:04:40
实体类package com.whty.entity;public class user {private int id;private string name;private int age;pub...
实体类
package com.whty.entity; public class user { private int id; private string name; private int age; public user(int id, string name, int age) { super(); this.id = id; this.name = name; this.age = age; } public int getid() { return id; } public void setid(int id) { this.id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } public int getage() { return age; } public void setage(int age) { this.age = age; } @override public string tostring() { return "user [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
测试类
package com.whty.test; import java.util.arraylist; import java.util.collections; import java.util.comparator; import java.util.list; import com.whty.entity.user; public class test { public static void main(string[] args) { list<user> list = new arraylist<>(); list.add(new user(1, "java", 20)); list.add(new user(2, "spark", 19)); list.add(new user(3, "hive", 21)); for(user user :list) { system.out.println("排序前:" + user.tostring()); } //实现排序 collections.sort(list, new comparator<user>() { @override public int compare(user u1, user u2) { if(u1.getage() > u2.getage()) { //return -1:即为正序排序 return -1; }else if (u1.getage() == u2.getage()) { return 0; }else { //return 1: 即为倒序排序 return 1; } } }); for(user user :list) { system.out.println("排序后:" + user.tostring()); } } }
运行结果
排序前:user [id=1, name=java, age=20]
排序前:user [id=2, name=spark, age=19]
排序前:user [id=3, name=hive, age=21]
排序后:user [id=3, name=hive, age=21]
排序后:user [id=1, name=java, age=20]
排序后:user [id=2, name=spark, age=19]
以上就是java如何实现list自定义排序的详细内容,更多关于java list自定义排序的资料请关注其它相关文章!