【发布时间】:2013-12-27 18:10:35
【问题描述】:
如何在 Dart 中获取 List 的最小值和最大值。
[1, 2, 3, 4, 5].min //returns 1
[1, 2, 3, 4, 5].max //returns 5
我确定我可以 a) 编写一个简短的函数或 b) 复制然后对列表进行排序并选择最后一个值,
但我正在寻找是否有更原生的解决方案。
【问题讨论】:
标签: dart
如何在 Dart 中获取 List 的最小值和最大值。
[1, 2, 3, 4, 5].min //returns 1
[1, 2, 3, 4, 5].max //returns 5
我确定我可以 a) 编写一个简短的函数或 b) 复制然后对列表进行排序并选择最后一个值,
但我正在寻找是否有更原生的解决方案。
【问题讨论】:
标签: dart
int minF() {
final mass = [1, 2, 0, 3, 5];
mass.sort();
return mass[0];
}
【讨论】:
如果您的列表为空,reduce 将抛出错误。
您可以使用fold 代替reduce。
// nan compare to any number will return false
final initialValue = number.nan;
// max
values.fold(initialValue, (previousValue, element) => element.value > previousValue ? element.value : previousValue);
// min
values.fold(initialValue, (previousValue, element) => element.value < previousValue ? element.value : previousValue);
它也可以用来计算总和。
final initialValue = 0;
values.fold(initialValue, (previousValue, element) => element.value + previousValue);
虽然fold 在获取最小值/最大值方面并不比reduce 干净,但它仍然是一种执行更灵活操作的强大方法。
【讨论】:
根据地图对象列表的条件使用 reduce 获取最小值/最大值的示例
Map studentA = {
'Name': 'John',
'Marks': 85
};
Map studentB = {
'Name': 'Peter',
'Marks': 70
};
List<Map> students = [studentA, studentB];
// Get student having maximum mark from the list
Map studentWithMaxMarks = students.reduce((a, b) {
if (a["Marks"] > b["Marks"])
return a;
else
return b;
});
// Get student having minimum mark from the list (one liner)
Map studentWithMinMarks = students.reduce((a, b) => a["Marks"] < b["Marks"] ? a : b);
另一个使用 reduce 根据类对象列表的条件获取最小值/最大值的示例
class Student {
final String Name;
final int Marks;
Student(this.Name, this.Marks);
}
final studentA = Student('John', 85);
final studentB = Student('Peter', 70);
List<Student> students = [studentA, studentB];
// Get student having minimum marks from the list
Student studentWithMinMarks = students.reduce((a, b) => a.Marks < b.Marks ? a : b);
【讨论】:
对于空列表:如果列表为空,则返回 0,否则返回最大值。
List<int> x = [ ];
print(x.isEmpty ? 0 : x.reduce(max)); //prints 0
List<int> x = [1,32,5];
print(x.isEmpty ? 0 : x.reduce(max)); //prints 32
【讨论】:
假设列表不为空,您可以使用Iterable.reduce:
import 'dart:math';
main(){
print([1,2,8,6].reduce(max)); // 8
print([1,2,8,6].reduce(min)); // 1
}
【讨论】:
[maxOnEmpty, ...list].reduce(max)。
[1,2,8,6].fold(0, max) 会成功的。
[].fold(0, max) 引发错误。 @AlexSemeniuk
您现在可以使用an extension as of Dart 2.6 实现此目的:
import 'dart:math';
void main() {
[1, 2, 3, 4, 5].min; // returns 1
[1, 2, 3, 4, 5].max; // returns 5
}
extension FancyIterable on Iterable<int> {
int get max => reduce(math.max);
int get min => reduce(math.min);
}
【讨论】:
如果您不想导入dart: math,但仍想使用reduce:
main() {
List list = [2,8,1,6]; // List should not be empty.
print(list.reduce((curr, next) => curr > next? curr: next)); // 8 --> Max
print(list.reduce((curr, next) => curr < next? curr: next)); // 1 --> Min
}
【讨论】:
dates.reduce((current, next) => current.compareTo(next) > 0 ? current : next) 最接近 LINQ 类语法。