MayNotBe
MayNotBe

Reputation: 2140

Sort Hashmap keys by date property of value

I have:

var schedulesByMonth = HashMap<String, MutableList<Schedule>>()

A Schedule has a startDate: Date property.

I'm starting with a giant list of Schedule objects and sorting them into the hashmap by month. So if the startDate on the Schedule object is June 2018 it goes into the list for the key June 2018.

This is all good but I need the keys for a picker sorted correctly by month:

schedulesByMonth.keys

if that array is ["July 2018", "August 2018", "June 2018"] I need it to be ["June 2018", "July 2018", "August 2018"].

I know I can make a sortedMap:

val sorted = schedulesByMonth.toSortedMap(compareBy<String> {

    }

But that only sorts the keys (String). How can I make it be the value (MutableList<Schedule>) so I can sort by the startDate of one of the Schedules?

Upvotes: 3

Views: 3032

Answers (2)

s1m0nw1
s1m0nw1

Reputation: 81929

You can sort the entries with sortedWith, which takes a comparator as its argument. Comparators can be created with compareBy easily:

schedulesByMonth.entries.sortedWith(compareBy({ it.value[0].startDate })

Upvotes: 7

LaskoS07
LaskoS07

Reputation: 1

I think that the main problem here is the wrong key class. Just replace Strings with Dates, and everything will be a lot easier.

Upvotes: 0

Related Questions