Siraj Sumra
Siraj Sumra

Reputation: 964

How to group items of Arraylist of time in HashMap in Kotlin?

I need to group the times together like 02:10 PM, 02:30 PM should come in group 02:00 PM - 03:00 PM. I am getting the all times in yyyy-MM-dd'T'HH:mm:ss.SSS+00:00 format. How to group the time together in 02:10 PM format?

Currently I converted them in hh:mm aa format and got the list, How to group them in Arraylists and finally store them in Map, So that I can list the times in Recyclerview?

Upvotes: 0

Views: 4565

Answers (1)

hotkey
hotkey

Reputation: 148079

Try something like this (given items with the time values stored in timeString):

val format = SimpleDateFormat("hh:mm aa")
val calendar = GregorianCalendar.getInstance()

val groups = items.groupBy { item ->
    val date = format.parse(item.timeString)
    calendar.setTime(date)
    calendar.get(Calendar.HOUR_OF_DAY)
}

(runnable demo)

See:

Upvotes: 5

Related Questions