In this shot, we will learn how to sort Map
by value using:
SplayTreeMap
and from()
methodfromEntries()
method and List sort()
methodSplayTreeMap
and from()
methodThe following code shows how to sort Map by value:
import 'dart:collection'; void main() { var fruits = {1: 'Orange', 4: 'Banana', 6: 'Pawpaw',3: 'Apple', 5: 'Mango', 2: 'Avocado'}; print(fruits); // sorting map by value var sortByValue = new SplayTreeMap<int, String>.from( fruits, (key1, key2) => fruits[key1].compareTo(fruits[key2])); print("***Sorted Map by value***"); print(sortByValue); }
In the code above, we created a sorted Map by values from the original Map fruits
. We passed the from
function a comparison function called compareTo()
, which compares the values of the pairs in the Map
.
fromEntries()
method and List sort()
methodThe following code shows how to sort Map by value:
void main() { var fruits = {1: 'Orange', 4: 'Banana', 6: 'Pawpaw',3: 'Apple', 5: 'Mango', 2: 'Avocado'}; print(fruits); var sortMapByValue = Map.fromEntries( fruits.entries.toList() ..sort((e1, e2) => e1.value.compareTo(e2.value))); print("***Sorted Map by value***"); print(sortMapByValue); }
RELATED TAGS
CONTRIBUTOR
View all Courses