How to sort map's values?

后端 未结 4 1102
心在旅途
心在旅途 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:14

    A function that does sort a Map of List on their length.

    import 'dart:collection';
    
    /// sorts the ListMap (== A Map of List) on the length
    /// of the List values.
    LinkedHashMap sortListMap(LinkedHashMap map) {
        List mapKeys = map.keys.toList(growable : false);
        mapKeys.sort((k1, k2) => map[k1].length - map[k2].length);
        LinkedHashMap resMap = new LinkedHashMap();
        mapKeys.forEach((k1) { resMap[k1] = map[k1] ; }) ;        
        return resMap;
    }
    

    result for :

    var res = sortListMap(chordtypes);
    print(res);
    

    ==>

    { omit3: [0, 7], 
      maj: [0, 4, 7], 
      sus2: [0, 2, 7], 
      sus4: [0, 5, 7], 
      #5: [0, 4, 8], 
      M7: [0, 4, 7, 11], 
      m7: [0, 3, 7, 10], 
      6: [0, 4, 7, 9], 
      9: [0, 4, 7, 10, 14], 
      +9: [0, 4, 8, 10, 14], 
      +7b9#11: [0, 4, 8, 10, 13, 18] }
    

提交回复
热议问题