简体   繁体   中英

Dart: sort list of Strings by frequency

I'm trying to sort a list by frequency.

List myList = ["a", "b", "c", "d", "e", "f", "d", "d", "e"];

My expected output would be that the list is sorted on frequency & has no duplicated elements.

(myList has 3x "d" and 2x "e").

List output = ["d", "e", "a", "b", "c", "f"];

What's the most efficient way to do it?

Thanks in advance!


Is it also possible to do the same system with a List of Maps/Objects?

List myList2 = [{"letter": a, "info": myInfo}, {"letter": b, "info": myInfo}, ...]

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM