Cristian Boariu
Cristian Boariu

Reputation: 9621

ordering timestamps in a Map

I have a List of some tuples, one if this tuple contains a timestamp. I try to order this list by timestamp and convert to map, like:

println(s"--list before order ${vendingMachineResults.map(v => v._5.timestamp)}")

val vendingMachineResultsGroupedByTimestamp =
  vendingMachineResults.sortBy(v1 => 
    (new DateTime(v1._5.timestamp)).toDate()
  ).flatMap(vendingMachineResult =>    
    Map(vendingMachineResult._5.timestamp -> vendingMachineResult)
  ).toMap

println(s"--Map with vending machines ordered by timestamp: ${vendingMachineResultsGroupedByTimestamp.keys}")

but the output is wrong:

--List before ordering: 
List(2012-04-16 14:33:34.807, 
2012-02-16 14:52:25.715, 
2012-06-18 14:52:25.715, 
2012-07-10 14:54:19.651, 
2012-07-16 14:54:19.651)
--Map with vending machines ordered by timestamp: 
Set(2012-04-16 14:33:34.807, 
    2012-02-16 14:52:25.715, 
    2012-06-18 14:52:25.715, 
    2012-07-16 14:54:19.651, 
    2012-07-10 14:54:19.651)

Does anyone have an idea what I am doing wrong? I expect timestamps to be in ascending order but they aren't.

Upvotes: 0

Views: 727

Answers (2)

Rick-777
Rick-777

Reputation: 10258

Maps do not preserve order, so the sorted ordering is lost. SortedMap is the main alternative that would overcome this problem.

Also, you could consider using a ListMap, which retains its members in the order in which they were added. The disadvantage of ListMap is that many operations take linear time, though.

Upvotes: 0

Rex Kerr
Rex Kerr

Reputation: 167901

Maps do not preserve order, so your sorting is thrown away again. You can use a SortedMap if it is essential that your map stay sorted. If you want a nonstandard ordering, you can specify one in a TreeMap.

Upvotes: 2

Related Questions