Java排序列表对象按日期升序 [英] Java sort list object by date ascending
本文介绍了Java排序列表对象按日期升序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想按日期升序按一个参数(日期格式为"YYYY-MM-DD HH:mm")对我的对象列表进行排序.我找不到正确的解决方案.在python中,使用lambda可以很容易地对其进行排序,但是在Java中,它存在问题.
I'd like to sort list of my objects by one argument it's date in format "YYYY-MM-DD HH:mm" by ascending order. I can't find a right solution. In python It's easily to sort it using lambda, but in Java I've a problem with it.
for (Shop car : cars) {
Collections.sort(cars, new Comparator<Shop>() {
@Override
public int compare(final Shop car, final Shop car) {
return car.getDate().compareTo(arc.getDate());
}
});
提前谢谢!
推荐答案
可以尝试一下.我认为它将起作用:
Can you try that. I think it will work:
SimpleDateFormat f = new SimpleDateFormat("YYYY-MM-DD HH:mm");
Stream<Date> sorted = l.stream().map(a->{
try {
return f.parse(a);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}).sorted();
更新: 以及是否需要列表:
UPDATE: and if you want a list:
List sorted = l.stream().map(a->{
try {
return f.parse(a);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}).sorted().collect(Collectors.toList());
已更新:(使用汽车"进行更新的问题)
UPDATED: (as question updated using "cars")
SimpleDateFormat f = new SimpleDateFormat("YYYY-MM-DD HH:mm");
List<Car> sorted = cars.stream().sorted(
(a,b)->
{
try {
return f.parse(a.getDate()).compareTo(f.parse(b.getDate()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
).collect(Collectors.toList());
这篇关于Java排序列表对象按日期升序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文