Android笔记App:按字符串日期时间排序ArrayList时thenComparing报错排查
问题分析与修复方案
核心错误点
用LocalDate解析时间字符串
你在thenComparing中调用LocalDate.parse(o.getTime(), t),但LocalDate仅用于处理日期(年/月/日),不包含时间维度。解析hh:mm格式的纯时间字符串必须使用LocalTime类,用LocalDate解析会直接抛出异常。排序方向不符合需求
当前Comparator默认按日期、时间升序排列(旧条目在前),但你需要最新条目在顶部,必须对整个比较器做逆序处理。潜在格式歧义
hh:mm是12小时制格式,需要配合AM/PM标记(如03:45 PM)才能正确解析。如果你的时间是24小时制存储(如15:45),必须把格式改为HH:mm(大写H对应24小时制),否则会解析失败。
修复后的代码
public static ArrayList<Note> loadAll(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_PREF, Context.MODE_PRIVATE); ArrayList<Note> notes = new ArrayList<>(); Set<String> noteIds = sharedPreferences.getStringSet(ID_KEY, null); if (noteIds != null) { for (String noteId : noteIds) { notes.add(load(context, noteId)); } } DateTimeFormatter dateFormatter; DateTimeFormatter timeFormatter; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy"); // 若为24小时制时间用HH:mm,12小时制带AM/PM用hh:mm a timeFormatter = DateTimeFormatter.ofPattern("HH:mm"); notes.sort(Comparator .comparing(o -> LocalDate.parse(o.getDate(), dateFormatter)) .thenComparing(o -> LocalTime.parse(o.getTime(), timeFormatter)) // 逆序实现最新条目置顶 .reversed()); } return notes; }
额外注意事项
- 确保
Note类的getTime()返回的字符串与timeFormatter格式完全匹配:- 24小时制时间必须是
00:00至23:59格式 - 12小时制时间需包含AM/PM标记(如
03:45 PM),同时格式改为hh:mm a
- 24小时制时间必须是
内容的提问来源于stack exchange,提问作者amarradi
相关产品推荐
相关产品推荐

