How to sort map's values?

后端 未结 4 1075
心在旅途
心在旅途 2021-01-06 11:45

Can someone give me a hint? I want to sort a map\'s values by the length of the lists.

var chordtypes = {
  \"maj\": [0, 4, 7],
  \"M7\": [0, 4, 7, 11],
  \"         


        
4条回答
  •  囚心锁ツ
    2021-01-06 12:22

    Building on @Leonardo Rignanese's answer. An extension function for a more functional approach:

    extension MapExt on Map {
      Map sortedBy(Comparable value(U u)) {
        final entries = this.entries.toList();
        entries.sort((a, b) => value(a.value).compareTo(value(b.value)));
        return Map.fromEntries(entries);
      }
    }
    

    General usage:

    foos.sortedBy((it) => it.bar);
    

    Usage for OP:

    final sortedChordtypes = chordtypes.sortedBy((it) => it.length);
    

    Gist here: https://gist.github.com/nmwilk/68ae0424e848b9f05a8239db6b708390

提交回复
热议问题