Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
map
value
communitycreator

How to create a sorted map by value in Dart

Maria Elijah

In this shot, we will learn how to sort Map by value using:

  1. The SplayTreeMap and from() method
  2. The Map fromEntries() method and List sort() method

SplayTreeMap and from() method

The 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.

Map fromEntries() method and List sort() method

The 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

dart
map
value
communitycreator
RELATED COURSES

View all Courses

Keep Exploring