user1865027
user1865027

Reputation: 3657

how can you sort by date for an ArrayList with TreeMap as value

in my code I have ArrayList<TreeMap<String, Object>>. What TreeMap would have is the key and value. there is a key named sent_date with the value in format of yyyy-MM-DD HH:MM:SS. I can't find a way to sort this list...Can someone please help? thanks.

Upvotes: 0

Views: 633

Answers (2)

Mark Peters
Mark Peters

Reputation: 81134

In Java 8, this would be (for a sort that modifies the list):

DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
list.sort(Comparator.comparing(m -> LocalDateTime.parse(m.get("sent_date"), format)));

Or if you want to keep the original list:

newList = list.stream()
              .sorted(Comparator.comparing(...))
              .collect(Collectors.toList());

Upvotes: 1

Thilo
Thilo

Reputation: 262794

You can use Collections.sort(list, comparator), where you have to implement a Comparator<Map<String,?>> to do what you need (i.e. retrieve the sent_date from two maps and compare those).

Upvotes: 1

Related Questions