java - 如何在 Android Studio 的自定义 Arraylist 中对日期进行排序?
问题描述
我在我的应用程序中添加了一项功能,该功能允许用户填写过去日期的条目,如果今天是 2020 年 3 月 14 日,那么它可以让您填写 2020 年 3 月 10 日(或任何其他日期)的条目。但是我在对我的数组列表进行排序时遇到问题,这样所有具有相同日期的条目都在数组列表中。
我在自定义 ListView 中向用户显示条目,因此为了使我的应用程序用户友好,我想让所有具有相同日期的条目一起出现。
我有一个自定义数组列表,它接受费用名称(字符串)、金额(字符串)和日期(字符串)
ArrayList<ExpenseData> customArrayList=new ArrayList<ExpenseData>();
如果您需要任何其他信息,请询问...谢谢!
解决方案
您可以使用以下方法按日期对列表进行排序。
Collections.sort(list, (item1, item2) -> {
Date date1 = stringToDate(item1.getDate());
Date date2 = stringToDate(item2.getDate());
if (date1 != null && date2 != null) {
boolean b1;
boolean b2;
if (isAscending) {
b1 = date2.after(date1);
b2 = date2.before(date1);
}else {
b1 = date1.after(date2);
b2 = date1.before(date2);
}
if (b1 != b2) {
if (b1) {
return -1;
}
if (!b1) {
return 1;
}
}
}
return 0;
});
public static Date stringToDate(String strDate) {
if (strDate == null)
return null;
// change the date format whatever you have used in your model class.
SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US);
Date date = null;
try {
date = format.parse(strDate);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
推荐阅读
- function - 从其他类成员函数(arduino)调用的类成员函数
- angularjs - AngularJS:检测当前页面是否使用 ui-router1.x 转换事件重新加载
- react-native - React Native 发布版本构建成功但不像调试那样工作
- python - 在多个 Python 模块上使用相同的 SQLite3 连接
- rest - 无法将实体添加到开箱即用的 jhipster 项目
- class - 使用非连续类 ID 的 TensorFlow 对象检测
- gatsby - 使用 gatsby 谷歌字体插件时仍然会出现无样式文本
- angular - 如何设置构造函数,使其没有太多参数?
- python - 无法在 python virtualenv 中安装本地包
- haskell - Cabal 中的“build-depends:”在哪里