我目前正在编写一个小型笔记应用程序,并将所有内容保存为共享首选项中的字符串。我现在想对笔记条目的概述进行排序,以便最新的条目始终显示在顶部。
问题是当我对笔记正文进行排序时,排序有效,但不能按日期和时间排序。日期以 dd.mm.yyyy 的形式存储,时间以 hh:mm 的形式存储在共享首选项中作为字符串。我怎样才能意识到这一点?
这是从sharedPref加载所有数据的方法。
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 d;
DateTimeFormatter t;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
d = DateTimeFormatter.ofPattern("dd.MM.yyyy");
t = DateTimeFormatter.ofPattern("hh:mm");
notes.sort(Comparator
.comparing(o -> LocalDate.parse(o.getDate(), d))
.thenComparing(o -> LocalDate.parse(o.getTime(), t)));
}
如果我仅将排序限制为日期,则它运行时不会出现错误。我可以按日期对列表进行排序。但是一旦我想使用 .thenComparing() 我的代码就有问题。我做错了什么?
这里我有两张截图。按正文排序和按日期排序
您可以将
String
日期转换为真实的 LocalDate
,然后排序:
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd-MM-yyyy");
notes.sort(
(String s1, String s2) -> LocalDate.parse(s1, f).compareTo(LocalDate.parse(s2, f)));
但最好的通用方法是将日期保留为应用程序中的
LocalDate
,而不是存储为文本。
蒂姆·比格莱森的回答是正确的。正如那里明智的建议,您应该将班级中的日期表示为 LocalDate
record 的示例类。
record Note ( LocalDate date , String text ) {}
样本数据。
LocalDate today = LocalDate.now() ; // Better to pass your specific desired/expected time zone (`ZoneId`).
List < Note > notes =
new ArrayList<>(
List.of(
new Note ( today , "today again" ) ,
new Note ( today , "today" ) ,
new Note ( today.plusDays( 1 ) , "tomorrow" ) ,
new Note ( today.minusDays( 1 ) , "yesterday" )
)
) ;
排序。不需要Collections.sort
课程。从 Java 8+ 开始,
List
有自己的 sort
方法。
notes.sort(
Comparator
.comparing( Note :: date ) // Two-level sort. First sort by date member field.
.thenComparing( Note :: text ) // Then sort by text member field.
) ;
如果您想始终保持排序顺序并消除任何重复项,请使用 /SortedSet
实现,例如
TreeSet
。
NavigableSet < Note > notes =
new TreeSet<>(
Comparator
.comparing( Note :: date )
.thenComparing( Note :: text )
) ;
无需致电sort
。当您添加元素时,它们会自动排序。
List
或
NavigableSet
。请参阅Java JEP 431。
SequencedCollection < Note > notes =
new TreeSet<>(
Comparator
.comparing( Note :: date )
.thenComparing( Note :: text )
) ;