More Than Five
More Than Five

Reputation: 10429

Convert map to a sorted list

I have a map...

Map(a -> List(a, a), b -> List(b, b), l -> List(l, l))

I can convert to a List

List((a,2), (l,2), (b,2))

By simply doing myMap.toList();

But I'd like to convert to a sorted list - which sorted on the first element of the tuple?

Any tips?

Thanks

Upvotes: 3

Views: 4190

Answers (2)

Aaron Novstrup
Aaron Novstrup

Reputation: 21017

Depending on your use case, it may be appropriate to use an ordered collection in the first place.

A TreeMap is a SortedMap -- it keeps the collection sorted as you insert/remove values, providing logarithmic lookup/insertion. If your sort operation happens frequently relative to insertion/removal, it may be worth trading off the constant time operations to have cheap access to sorted results.

A ListMap is a list-based map structure. Lookup/insertion are horribly inefficient, but this may be an appropriate choice if these operations happen relatively infrequently. You'll have to sort the list whenever you insert pairs.

Upvotes: 0

ghik
ghik

Reputation: 10764

Quick solution: myMap.toList.sortBy(_._1).

This is equivalent to myMap.toList.sortBy(tuple => tuple._1). The _1 gets first element from a tuple.

sortBy in general takes a function that maps sorted elements to some value and that value will be used to compare elements being sorted.

You can also write this more verbosely like this: myMap.toList.sortBy {case (key, _) => key}

Upvotes: 11

Related Questions