如何获得Dart中List的最小值和最大值.
[1, 2, 3, 4, 5].min //returns 1
[1, 2, 3, 4, 5].max //returns 5
Run Code Online (Sandbox Code Playgroud)
我确定我可以a)编写一个简短的函数或b)复制然后对列表进行排序并选择最后一个值,
但我希望看看是否有更原生的解决方案,如果有的话.
Ale*_*uin 54
假设列表不为空,您可以使用Iterable.reduce:
import 'dart:math';
main(){
print([1,2,8,6].reduce(max)); // 8
print([1,2,8,6].reduce(min)); // 1
}
Run Code Online (Sandbox Code Playgroud)
Mur*_*dla 36
如果您不想导入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
}
Run Code Online (Sandbox Code Playgroud)
cre*_*not 21
现在,您可以做到这一点的extension是飞镖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);
}
Run Code Online (Sandbox Code Playgroud)
Say*_*yka 11
根据 Map 对象列表的条件使用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);
Run Code Online (Sandbox Code Playgroud)
另一个根据类对象列表的条件使用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);
Run Code Online (Sandbox Code Playgroud)
如果您的列表为空,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);
Run Code Online (Sandbox Code Playgroud)
它还可以用于计算总和。
final initialValue = 0;
values.fold(initialValue, (previousValue, element) => element.value + previousValue);
Run Code Online (Sandbox Code Playgroud)
尽管fold并不比reduce获取最小值/最大值更干净,但它仍然是执行更灵活操作的强大方法。
| 归档时间: |
|
| 查看次数: |
9575 次 |
| 最近记录: |