Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort list of maps where each map is a pair of key and another list of objects

I have the following list in Dart, which is a List of Map which maps a key to a list of MyClass objects:

class MyClass {
  final String name;
  final int age;

  MyClass({
    required this.name,
    required this.age,
  });
}

void main() { 
  MyClass obj1 = MyClass(name: "aa", age: 10);
  MyClass obj2 = MyClass(name: "bb", age: 20);
  MyClass obj3 = MyClass(name: "cc", age: 30);
  MyClass obj4 = MyClass(name: "dd", age: 40);
  MyClass obj5 = MyClass(name: "ee", age: 50);
  MyClass obj6 = MyClass(name: "ff", age: 60);
  
   List<Map<String, List<Object>>> myList = [
  { '3' : [obj1, obj2]},
  { '1' : [obj3, obj4]},
  { '2' : [obj5, obj6]},
];

  print(myList);
}

I need to sort this list based on keys in descending order so that keys need to be in the order ‘3’, ‘2’, ‘1’ in the main list.

How can I do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can give sort() on List a compare method which define how elements should be sorted. So in your case, we can do something like this:

void main() {
  List<Map<String, List<MyClass>>> myList = [
    { '3' : [MyClass(name: 'ifredom',age:23), MyClass(name: 'aaa',age:13)]},
    { '1' : [MyClass(name: 'JackMa',age:61), MyClass(name: 'bbb',age:33)]},
    { '2' : [MyClass(name: 'zhazhahui',age:48), MyClass(name: 'ccc',age:29)]}
  ];

  myList.forEach(print);
  // {3: [MyClass(name: ifredom, age: 23), MyClass(name: aaa, age: 13)]}
  // {1: [MyClass(name: JackMa, age: 61), MyClass(name: bbb, age: 33)]}
  // {2: [MyClass(name: zhazhahui, age: 48), MyClass(name: ccc, age: 29)]}

  myList.sort((a, b) => b.keys.first.compareTo(a.keys.first));

  myList.forEach(print);
  // {3: [MyClass(name: ifredom, age: 23), MyClass(name: aaa, age: 13)]}
  // {2: [MyClass(name: zhazhahui, age: 48), MyClass(name: ccc, age: 29)]}
  // {1: [MyClass(name: JackMa, age: 61), MyClass(name: bbb, age: 33)]}
}

class MyClass {
  final String name;
  final int age;

  MyClass({required this.name, required this.age,});

  @override
  String toString() => 'MyClass(name: $name, age: $age)';
}

Notice that we do assume here that each Map in your first List only contains one key and then sort based on this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading