其他分享
首页 > 其他分享> > list根据多个属性时间字符串排序

list根据多个属性时间字符串排序

作者:互联网

package com.example.demo.qqqq;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class TestArraySort {
public static void main(String[] args) {
List<person> list = new ArrayList<>();
list.add(new person(1,"2021-09-06"));
list.add(new person(2,"2021-09-08"));
list.add(new person(2,"2021-09-03"));
list.add(new person(3,"2021-09-07"));
list.add(new person(4,"2021-09-05"));
List newList = list.stream().sorted((o1, o2) -> {
int num = Integer.compare(o2.getAge(),o1.getAge());
if (num == 0) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d1 = format.parse(o1.getBirth());
Date d2 = format.parse(o2.getBirth());
return Long.compare(d2.getTime(), d1.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
return num;
}).collect(Collectors.toList());
newList.forEach(e->{
System.out.println(e.toString());
});

}
private static class person{
private int age;
private String birth;

@Override
public String toString() {
return "person{" +
"age=" + age +
", birth='" + birth + '\'' +
'}';
}

public person(int age, String birth) {
this.age = age;
this.birth = birth;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getBirth() {
return birth;
}

public void setBirth(String birth) {
this.birth = birth;
}
}
}

标签:age,list,person,birth,字符串,new,排序,public
来源: https://www.cnblogs.com/6kuaifuji/p/15224203.html