如何对时间戳列表进行排序?

K R*_*Roy 1 java sorting android timestamp date

我有一个时间戳(长)列表,其中我必须根据时间或添加的列表对列表进行排序。

我已经尝试和搜索过,但它现在可以工作了。

 Collections.sort(vehicles, new Comparator<VehicleListModel.Vehicle>() {
                @Override
                public int compare(VehicleListModel.Vehicle o1, VehicleListModel.Vehicle o2) {
                    try {
                        DateFormat format = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
                        return format.parse(o1.getCreated()).compareTo(format.parse(o2.getCreated()));
                    } catch (Exception e) {
                        e.printStackTrace();
                        return 0;
                    }
                }
            });
            customerListAdapter.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)

它不起作用然后我尝试了 这个但它Date(timeStamp)已被弃用

请帮忙

Dar*_*hta 6

如果getCreated返回 aDate那么您可以使用比较两个日期compareTo并根据此比较对列表进行排序,例如:

List<VehicleListModel.Vehicle> list = new ArrayList<>();
list.sort((e1, e2) -> e1.getCreated().compareTo(e2.getCreated()));
Run Code Online (Sandbox Code Playgroud)

更新

如果getCreated返回long值,那么您可以将其装箱并使用类compareTo的方法Long,例如:

List<ChainCode> list = new ArrayList<ChainCode>();
list.sort((e1, e2) -> new Long(e1.getCreated()).compareTo(new Long(e2.getCreated())));
Run Code Online (Sandbox Code Playgroud)