#2493 Anyone for Map.sort() ?

SlimerDude Fri 13 Nov 2015

Something else I do fairly frequently is sort Maps. It's always nice to iterate over maps in some predefined order, be it alphabetical or otherwise. So how about:

M Map.sort(|K ,K->Int|? c := null)

Where K are the Map keys.

I was wondering about passing the map values into the closure too, but that complicates things and they're easily obtained from the Map anyway. True, there could be separate sortByKey() and sortByVal() methods - but that's over complicating it also.

The returned Map would obviously have to be an ordered Map, which is fine. But it'd be nice if Map.sort() was synonymous with List.sort() - and List.sort() sorts in place. That means calling Map.sort() could convert your unordered Map into an ordered one - which isn't too bad, but what if the Map is case-insensitive? (Note that Maps currently can not be ordered AND case-sensitive.)

Hmm... I'd be happy if Map.sort() just returned an ordered copy.

brian Wed 18 Nov 2015

That seems a bit obtuse to add a method to Map which would require generating a new map in most cases, so it would be very different than how List.sort works. Given how it easy it is to use map.vals.sort or map.keys.sort' I've found that leads to very readable code

Login or Signup to reply.