Prompt Title: Sort Map in Dart.

Created 1 year ago
Votes 0
Views 156 times
IT
0

Prompt Detail:

In Dart, you can sort a Map by converting it to a list of key-value pairs using the entries property of the Map, sorting the list, and then creating a new Map from the sorted list.

Here's an example of sorting a Map by its keys in ascending order:

javascript
Map<String, int> unsortedMap = { 'apple': 3, 'banana': 1, 'orange': 2, }; List<MapEntry<String, int>> sortedList = unsortedMap.entries.toList() ..sort((a, b) => a.key.compareTo(b.key)); Map<String, int> sortedMap = Map.fromEntries(sortedList); print(sortedMap); // Output: {apple: 3, banana: 1, orange: 2}

In the example above, we first define an unsorted map of strings and integers. We then convert the map to a list of MapEntry objects using the entries property and the toList() method. We use the ..sort() method to sort the list in ascending order by the keys, which are strings. Finally, we create a new Map from the sorted list using the Map.fromEntries() constructor.

You can sort the Map by values instead of keys by modifying the comparison function in the ..sort() method. Here's an example of sorting a Map by its values in descending order:

javascript
Map<String, int> unsortedMap = { 'apple': 3, 'banana': 1, 'orange': 2, }; List<MapEntry<String, int>> sortedList = unsortedMap.entries.toList() ..sort((a, b) => b.value.compareTo(a.value)); Map<String, int> sortedMap = Map.fromEntries(sortedList); print(sortedMap); // Output: {apple: 3, orange: 2, banana: 1}

In this example, we use the compareTo() method of the value property to sort the list in descending order.

avatar
Lucas Acosta
Shared 1 prompt
Created 1 year ago

Leave a Comment

Related Tag Prompts

0
0
0
0
Split or Boolean Input?
10 months ago 2023-07-10 16:14:26 Bryan Bugyi
0
0
0
0
dart
3 months ago 2024-01-18 13:38:31 Undefined