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.
The following is the syntax to declare a SplayTreeMap
:
SplayTreeMap map = SplayTreeMap();
The following code shows how to sort a map by key:
import 'dart:collection';void main() {// Creating SplayTreeMapvar fruits = SplayTreeMap<int, String>();// Adding key-value pairsfruits[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 methodfruits.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.