List元素是对象,根据对象的某个属性排序
程序员文章站
2022-04-06 15:55:49
...
实体类
import java.util.Date;
public class User {
private Integer userId;
private String username;
private String password;
private Date birthday;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public User(Integer userId, String username, String password, Date birthday) {
this.userId = userId;
this.username = username;
this.password = password;
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
'}';
}
}
根据生日日期倒序
import com.example.demo.domain.User;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class TestListSort {
private static void ListSort(List<User> list) {
Collections.sort(list, new Comparator<User>() {
@Override
public int compare(User u1, User u2) {
try {
Date dt1 = u1.getBirthday();
Date dt2 = u2.getBirthday();
if (dt1.getTime() < dt2.getTime()) {
return 1;
} else if (dt1.getTime() > dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
});
}
public static void main(String[] args) {
List<User> users = new ArrayList<>();
User user1 = new User(1, "张三", "111111", string2Date("2000-09-17 22:33:45"));
User user2 = new User(2, "李四", "222222", string2Date("2002-06-15 22:33:45"));
User user3 = new User(3, "王五", "333333", string2Date("2002-06-03 22:33:45"));
User user4 = new User(4, "小明", "444444", string2Date("1993-09-17 22:33:45"));
User user5 = new User(5, "蛋蛋", "555555", string2Date("2010-06-19 22:33:45"));
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
users.add(user5);
ListSort(users);
System.err.println(users);
}
public static Date string2Date(String str){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parse = null;
try {
parse = dateFormat.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return parse;
}
}
上一篇: PAT B1010 一元多项式求导
推荐阅读
-
js删除对象中的某个元素(js删除对象属性的方法)
-
js删除对象中的某个元素(js删除对象属性的方法)
-
js 根据对象数组中的属性进行排序实现代码
-
如果list中的元素是基本类型或者String类型,那么sout(list)是可以直接打印出元素的,如果是对象类型,就会报错。
-
JS 中对数组按照数组中某个对象的属性值进行排序
-
给集合中的元素(实体类对象)按照某个属性进行排序
-
List用法:根据对象属性排序、筛选、去重
-
List对象集合按照属性排序、分组,并按照分组后每组的多少进行排序。
-
C# List 根据对象属性去重的四种方法对比
-
根据对象的某一属性进行排序的js代码(如:name,age)_javascript技巧