Skip to content
Advertisement

How to sort ‘Map’ values in Scala against multiple factors?

I have a Map (datatype) with the following data structure:

JavaScript

It contains a String and a ‘Time’ object. The ‘Time’ object is made up from my own class. Below you can see what it consists of:

JavaScript

I have saved all my data into this ‘Map’ variable. But there is one problem: I want to sort the values in this ‘Map’ variable based on multiple things, but I can’t find any way to make it work.

For example. I have stored the following data within this map:

JavaScript

I want to sort the values in order (earliest time to latest time). This includes comparing multiple factors. First compare each daysSinceEpoch, then hours, minutes and seconds.

I want to transform the map into the following down below:

JavaScript

Does anyone know of an efficient way to do this? Unfortunately I can’t..

Advertisement

Answer

It sounds like a ListMap is what you want.

From the ScalaDocs page: “Entries are stored internally in reversed insertion order, which means the newest key is at the head of the list.”

So to transit from the current Map to a ListMap:

JavaScript

testing:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement