java Java按日期升序对列表对象进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43426669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java sort list object by date ascending
提问by stackish
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.
我想通过一个参数对我的对象列表进行排序,它的日期格式为“YYYY-MM-DD HH:mm”,按升序排列。我找不到正确的解决方案。在 python 中使用 lambda 很容易对其进行排序,但在 Java 中我遇到了问题。
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());
}
});
Thanks in advance!
提前致谢!
采纳答案by strash
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());
回答by Nestor Sokil
If you are using java 8:
如果您使用的是 Java 8:
DateTimeFormatter fm = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
objects.sort((o1, o2) -> LocalDateTime.parse(o1.getDateStr(), fm)
.compareTo(LocalDateTime.parse(o2.getDateStr(), fm)));
And java 7:
和Java 7:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Collections.sort(objects, new Comparator<YourObjectType>() {
public int compare(YourObjectType o1, YourObjectType o2) {
try {
return df.parse(o1.getDateStr()).compareTo(df.parse(o2.getDateStr()));
} catch(ParseException pe) {
// handle the way you want...
}
}
});
回答by ZhekaKozlov
Clean solution without ParseException
:
不含ParseException
以下物质的清洁溶液:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
list.sort(Comparator.comparing(shop -> LocalDateTime.parse(shop.getDate(), formatter)));
回答by SmashCode
public boolean before(Date when)
true if and only if the instant of time represented by this Date object is strictly earlier than the instant represented by when; false otherwise.
公共布尔值之前(日期时间)
当且仅当此 Date 对象表示的时刻严格早于 when 表示的时刻时才为真;否则为假。
please refer java docs for more info https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#before-java.util.Date-
有关更多信息,请参阅 java 文档https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#before-java.util.Date-
Or you can use aftermethod from Date Class inplace of before
或者您可以使用Date 类中的after方法代替before
package com.stackoverflow.DataSortReverse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
class Car{
private String name;
private Date date;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Car(String name, Date date) {
super();
this.name = name;
this.date = date;
}
@Override
public String toString() {
return "Car [date=" + date + "]";
}
}
public class DateSort {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
List<Car> carList = new ArrayList<Car>();
try {
carList.add(new Car("car1",dateFormat.parse("2017-01-10")));
carList.add(new Car("car1",dateFormat.parse("2017-02-10")));
carList.add(new Car("car1",dateFormat.parse("2017-02-30")));
carList.add(new Car("car1",dateFormat.parse("2017-01-09")));
} catch (ParseException e) {
System.out.println(e.getMessage());
}
/*
* if you wish to change sorting order just
* replace -1 with 1 and 1 with -1
*
*
* date1.before(date2) returns true when date1 comes before date2
* in calendar
*
* java docs :: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#before-java.util.Date-
* */
Collections.sort(carList, new Comparator<Car>() {
@Override
public int compare(Car o1, Car o2) {
if(o1.getDate().before(o2.getDate())){
return -1;
}
return 1;
}
});
System.out.println(carList);
}
}
回答by Joey deVilla
A revision of my solution. If you define the following comparator class...
我的解决方案的修订版。如果您定义以下比较器类...
class ShopDateComparator implements Comparator<Shop> {
@Override
public int compare(Shop shop1, Shop shop2) {
return shop1.getDate().toLowerCase().compareTo(shop2.getDate().toLowerCase());
}
}
...then all you need to do sort cars
(which I'm assuming is a list of objects of type Shop
) is:
...那么你需要做的所有排序cars
(我假设是类型的对象列表Shop
)是:
Collections.sort(cars, new ShopDateComparator());