It is not difficult to do that even without using package:collection
.
List myList = ['a', 'b', 'c', 'd', 'e', 'f', 'd', 'd', 'e'];
// Put the number of letters in a map where the letters are the keys.
final map = <String, int>{};
for (final letter in myList) {
map[letter] = map.containsKey(letter) ? map[letter] + 1 : 1;
}
// Sort the list of the map keys by the map values.
final output = map.keys.toList(growable: false);
output.sort((k1, k2) => map[k2].compareTo(map[k1]));
print(output); // [d, e, a, b, c, f]
As for the second one, your desired output is unclear, but assuming that the values corresponding to the key letter
are String
and that you need exactly the same output as that of the first one, you can achieve it in a very similar way.
List myList2 = [
{'letter': 'a', 'info': 'myInfo'},
{'letter': 'b', 'info': 'myInfo'},
{'letter': 'c', 'info': 'myInfo'},
{'letter': 'd', 'info': 'myInfo'},
{'letter': 'e', 'info': 'myInfo'},
{'letter': 'f', 'info': 'myInfo'},
{'letter': 'd', 'info': 'myInfo'},
{'letter': 'd', 'info': 'myInfo'},
{'letter': 'e', 'info': 'myInfo'},
];
final map2 = <String, int>{};
for (final m in myList2) {
final letter = m['letter'];
map2[letter] = map2.containsKey(letter) ? map2[letter] + 1 : 1;
}
final output2 = map2.keys.toList(growable: false);
output2.sort((k1, k2) => map2[k2].compareTo(map2[k1]));
print(output2); // [d, e, a, b, c, f]