Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java按日期升序排序列表对象_Java_Sorting - Fatal编程技术网

Java按日期升序排序列表对象

Java按日期升序排序列表对象,java,sorting,Java,Sorting,我想按一个参数对我的对象列表进行排序,它的日期格式为“YYYY-MM-DD HH:MM”,升序为。我找不到正确的解决办法。在python中,使用lambda很容易对其进行排序,但在Java中,我遇到了一个问题 for (Shop car : cars) { Collections.sort(cars, new Comparator<Shop>() { @Override public int c

我想按一个参数对我的对象列表进行排序,它的日期格式为“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());
            }
        });
用于(车间车辆:车辆){
Collections.sort(cars,newcomparator(){
@凌驾
公共int比较(最终车间车辆,最终车间车辆){
return car.getDate().compareTo(arc.getDate());
}
});

提前谢谢!

你能试试吗。我想它会有用的:

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();
更新:(使用“汽车”更新问题)

SimpleDateFormat f=新的SimpleDateFormat(“YYYY-MM-DD HH:MM”);
列表排序=cars.stream().sorted(
(a、b)->
{
试一试{
返回f.parse(a.getDate()).compareTo(f.parse(b.getDate());
}捕获(解析异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回0;
}
).collect(Collectors.toList());

如果您使用的是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)));
和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...
                }
        }
    });
DateFormat df=新的简化格式(“yyyy-MM-dd-HH:MM”);
排序(对象,新比较器(){
公共int比较(YourObjectType o1,YourObjectType o2){
试一试{
返回df.parse(o1.getDateStr()).compareTo(df.parse(o2.getDateStr());
}捕获(解析异常pe){
//按你想要的方式处理。。。
}
}
});

我的解决方案的修订版。如果定义以下comparator类

class ShopDateComparator implements Comparator<Shop> {
  @Override
  public int compare(Shop shop1, Shop shop2) {
    return shop1.getDate().toLowerCase().compareTo(shop2.getDate().toLowerCase());
  }
}

无异常的清洁溶液ParseException:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
list.sort(Comparator.comparing(shop -> LocalDateTime.parse(shop.getDate(), formatter)));
之前的公共布尔值(日期和时间)

当且仅当此日期表示的时间瞬间 对象严格早于由when表示的瞬间;false 否则

有关更多信息,请参阅java文档

或者您可以使用日期类中的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);
    }

}
package com.stackoverflow.dataportreverse;
导入java.text.ParseException;
导入java.text.simpleDataFormat;
导入java.util.ArrayList;
导入java.util.Collections;
导入java.util.Comparator;
导入java.util.Date;
导入java.util.List;
班车{
私有字符串名称;
私人日期;
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
公共日期getDate(){
返回日期;
}
公共作废设置日期(日期){
this.date=日期;
}
公共汽车(字符串名称、日期){
超级();
this.name=名称;
this.date=日期;
}
@凌驾
公共字符串toString(){
返回“汽车[日期=”+日期+“]”;
}
}
公共类日期排序{
公共静态void main(字符串[]args){
SimpleDataFormat dateFormat=新SimpleDataFormat(“yyyy-MM-dd”);
List carList=new ArrayList();
试一试{
carList.add(新车(“car1”,dateFormat.parse(“2017-01-10”));
carList.add(新车(“car1”,dateFormat.parse(“2017-02-10”));
carList.add(新车(“car1”,日期格式解析(“2017-02-30”));
carList.add(新车(“car1”,dateFormat.parse(“2017-01-09”));
}捕获(解析异常){
System.out.println(e.getMessage());
}
/*
*如果您想更改排序顺序,只需
*将-1替换为1,将1替换为-1
* 
* 
*date1.before(date2)在date1早于date2时返回true
*日历中
* 
*java文档::https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#before-java.util.Date-
* */
Collections.sort(carList,newcomparator(){
@凌驾
公共整数比较(o1车、o2车){
如果(o2.getDate()之前的o1.getDate()){
返回-1;
}
返回1;
}
});
系统输出打印LN(carList);
}
}


这是一个日期还是那种类型的字符串?如果这是一个日期,你会使用哪种java对象?这是一个那种类型的字符串显示一些你尝试过的实际代码。这是java 8吗?如果不是,那很重要。我只列出了myOwnClass的数据对象,并使用了Collection.sort(那种列表);提示:只使用java.time类,而不要使用
Date
&
Calendar
类。如果没有解析异常,它会更清晰…:|但是它会抛出,所以我们必须处理它,我必须将对象列表放在哪里,是不是这个L(小写)?我为您的“汽车”列表实现了它谢谢!!!!但是我有一个汽车列表,里面有一个日期作为字符串,格式为“YYYY-MM-DD”,我想按这个日期排序我的答案只是一个指南,特定于代码的解决方案非常类似:
Collections.sort(汽车,(Shop shop1,Shop shop2)->shop1.date.toLowerCase().compareTo(shop2.date.toLowerCase())
不行,我已经试过你的解决方案了我已经修改了我的答案-检查一下,看看它是否对你有效。@joyedevilla The
.toLowerCase()
实际上是不需要的,因为字符串不包含任何字母,根据使用的日期时间格式,仅
0123456789:-
。它向我显示了一个错误:线程“main”java.time.format.DateTimeParseException中的异常:无法解析文本“2017-04-02”:无法从TemporalAccessor获取LocalDateTime:{},ISO解析为2017-04-02,类型为java.time.format.Parsedso,没有异常,但没有异常处理:D@stackish我想,这是因为您的一些日期不包含时间部分(例如,
2017-04-02
而不是
2017-04-02 12:00
)。我已将所有日期更改为格式“YYYY-MM-DD”没有几个小时,仍然给我exceptions@stac
Collections.sort(cars, new ShopDateComparator());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
list.sort(Comparator.comparing(shop -> LocalDateTime.parse(shop.getDate(), formatter)));
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);
    }

}