How to sort a Map by keys in Dart

To sort a Map, we can utilize the SplayTreeMap. Sorted keys are used to sort the SplayTreeMap.

A SplayTreeMap is a type of map that iterates keys in a sorted order. SplayTreeMap is a self-balancing binary tree. This means that frequently accessed items will be moved closer to the tree’s root.

Syntax

The following is the syntax to declare a SplayTreeMap:

SplayTreeMap map = SplayTreeMap();

Code

The following code shows how to sort a map by key:

import 'dart:collection';
void main() {
// Creating SplayTreeMap
var fruits = SplayTreeMap<int, String>();
// Adding key-value pairs
fruits[1] = 'Orange';
fruits[4] = 'Banana';
fruits[6] = 'Pawpaw';
fruits[3] = 'Apple';
fruits[5] = 'Mango';
fruits[2] = 'Avocado';
print("***Sorted map by keys**");
print(fruits);
// Iterating over map pairs using forEach method
fruits.forEach((key, val) {
print('{ key: $key, value: $val}');
});
}

In thecode above, we created a SplayTreeMap called fruits. By default, the keys are used to sort the pairs, which are sorted numerically and in ascending order.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources