如何按字符串格式的日期和时间对 ArrayList 进行排序[重复]

问题描述 投票:0回答:2

我目前正在编写一个小型笔记应用程序,并将所有内容保存为共享首选项中的字符串。我现在想对笔记条目的概述进行排序,以便最新的条目始终显示在顶部。

问题是当我对笔记正文进行排序时,排序有效,但不能按日期和时间排序。日期以 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() 我的代码就有问题。我做错了什么?

这里我有两张截图。按正文排序和按日期排序

java android sorting date arraylist
2个回答
4
投票

您可以将

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
,而不是存储为文本。


2
投票

蒂姆·比格莱森的回答是正确的。正如那里明智的建议,您应该将班级中的日期表示为 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. ) ;
如果您想始终保持排序顺序并消除任何重复项,请使用 

NavigableSet

/SortedSet
 实现,例如 
TreeSet

NavigableSet < Note > notes = new TreeSet<>( Comparator .comparing( Note :: date ) .thenComparing( Note :: text ) ) ;
无需致电

sort

。当您添加元素时,它们会自动排序。


顺便说一下,在 Java 21+ 中,我们可以使用

SequencedCollection

 作为更通用的接口,而不是 List
NavigableSet
。请参阅 
Java JEP 431

SequencedCollection < Note > notes = new TreeSet<>( Comparator .comparing( Note :: date ) .thenComparing( Note :: text ) ) ;
    
© www.soinside.com 2019 - 2024. All rights reserved.