对键是字符串,值是整型列表的映射进行排序的最佳方法是什么?
var userVotes = {
"arbourn": [1, 0, 7],
"burun": [2, 9, 0, 1],
"niko": [1, 0, 3, 10],
};
排序是基于列表(值)进行的。1.第一个值较高的列表胜出2.值相同的情况下,长度较大的列表胜出。3.否则,map (不是非常重要)的预期输出没有变化
var userVotes = {
"burun": [2, 9, 0, 1],
"arbourn": [1, 0, 7],
"niko": [1, 0, 3, 10],
};
性能标准-列表长度限制为<=100,键数限制为<=1000。
谢谢!
发布于 2020-05-05 07:06:41
这样的事情是可以做到的:
import 'dart:collection';
void main() {
final userVotes = {
"arbourn": [1, 0, 7],
"burun": [2, 9, 0, 1],
"niko": [1, 0, 3, 10],
"niko2": [1, 0, 3, 10, 0],
};
final sortedMap =
LinkedHashMap.fromEntries(userVotes.entries.toList()..sort(sortMethod));
sortedMap.forEach((key, value) => print('$key: $value'));
}
int sortMethod(MapEntry<String, List<int>> e1, MapEntry<String, List<int>> e2) {
final l1 = e1.value;
final l2 = e2.value;
final minLength = l1.length > l2.length ? l2.length : l1.length;
for (var i = 0; i < minLength; i++) {
if (l1[i] > l2[i]) {
return -1;
} else if (l1[i] < l2[i]) {
return 1;
}
}
return l2.length.compareTo(l1.length);
}
以下哪项输出:
burun: [2, 9, 0, 1]
arbourn: [1, 0, 7]
niko2: [1, 0, 3, 10, 0]
niko: [1, 0, 3, 10]
编辑
由于对映射进行排序并不是很好,因此更好的策略是将每个键-值对转换为一个UserVote
对象,该对象实现对其他UserVote
对象的compareTo
。此对象可以放入列表中并进行排序。
import 'dart:collection';
class UserVote implements Comparable<UserVote> {
final String name;
final List<int> list;
const UserVote(this.name, this.list);
@override
int compareTo(UserVote o) {
final minLength = list.length > o.list.length ? o.list.length : list.length;
for (var i = 0; i < minLength; i++) {
if (list[i] > o.list[i]) {
return -1;
} else if (list[i] < o.list[i]) {
return 1;
}
}
return o.list.length.compareTo(list.length);
}
@override
String toString() => '$name: $list';
}
void main() {
final userVotes = {
"arbourn": [1, 0, 7],
"burun": [2, 9, 0, 1],
"niko": [1, 0, 3, 10],
"niko2": [1, 0, 3, 10, 0],
};
final listOfUserVotes =
userVotes.entries.map((e) => UserVote(e.key, e.value)).toList();
listOfUserVotes.sort();
listOfUserVotes.forEach(print);
}
https://stackoverflow.com/questions/61607106
复制