如何在Dart中获取List的最小值和最大值。
[1, 2, 3, 4, 5].min //returns 1
[1, 2, 3, 4, 5].max //returns 5
我相信我可以 a) 写一个简短的函数或者 b) 复制并排序列表然后选择最后一个值,
但是我正在寻找是否有更本地的解决方案。
如何在Dart中获取List的最小值和最大值。
[1, 2, 3, 4, 5].min //returns 1
[1, 2, 3, 4, 5].max //returns 5
我相信我可以 a) 写一个简短的函数或者 b) 复制并排序列表然后选择最后一个值,
但是我正在寻找是否有更本地的解决方案。
假设该列表不为空,则可以使用Iterable.reduce:
import 'dart:math';
main(){
print([1,2,8,6].reduce(max)); // 8
print([1,2,8,6].reduce(min)); // 1
}
如果您不想导入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语法的东西。 - jnt现在,您可以使用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);
}
as
关键字在导入语句中可以为我解决问题。import 'dart:math' as math;
。 - someoneMap 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);
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
清晰,但它仍然是一个执行更灵活操作的强大方法。
void main() {
firstNonConsecutive([1,2,3,4,6,7,8]);
}
int? firstNonConsecutive(List<int> arr) {
var max = arr.reduce((curr, next) => curr > next? curr: next);
print(max); // 8 --> Max
var min = arr.reduce((curr, next) => curr < next? curr: next);
print(min); // 1 --> Min
return null;
}
对于空列表:如果列表为空,将返回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
minBy()
和maxBy()
功能来自collection包:import 'package:collection/collection.dart';
class Person {
final String name;
final int age;
Person(this.name, this.age);
@override
String toString() => '$name (age $age)';
}
main() {
final alice = Person('Alice', 30);
final bob = Person('Bob', 40);
final chris = Person('Chris', 25);
final dan = Person('Dan', 35);
final people = [alice, bob, chris, dan];
print('Youngest is ${minBy(people, (e) => e.age)}');
print('Oldest is ${maxBy(people, (e) => e.age)}');
print('First alphabetically is ${minBy(people, (e) => e.name)}');
print('Last alphabetically is ${maxBy(people, (e) => e.name)}');
print('Largest name length times age is ${maxBy(people, (e) => e, compare: (a, b) => (a.name.length * a.age).compareTo(b.name.length * b.age))}');
}
输出:
Youngest is Chris (age 25)
Oldest is Bob (age 40)
First alphabetically is Alice (age 30)
Last alphabetically is Dan (age 35)
Largest name length times age is Alice (age 30)
int minF() {
final mass = [1, 2, 0, 3, 5];
mass.sort();
return mass[0];
}
O(n log n)
,而最小值和最大值为O(n)
。 - Chuck Batson
[maxOnEmpty, ...list].reduce(max)
。 - Alexandre Ardhuin[1,2,8,6].fold(0, max)
就能达到效果。 - Alex Semeniuk[].fold(0,max)
会抛出错误。@AlexSemeniuk - PROgram52bcint biggestNum(List<int> numbers) => numbers.fold(0, max);
- Richard Sipher