Dart List min/max value

How do you get the min and max values of a List in Dart.

[1, 2, 3, 4, 5].min //returns 1
[1, 2, 3, 4, 5].max //returns 5

I'm sure I could a) write a short function or b) copy then sort the list and select the last value,

but I'm looking to see if there is a more native solution if there is any.

84896 次浏览

假设列表不是空的,你可以使用 可以,减少:

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
}

你现在可以通过 一个 extension的 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);
}

对于空列表: 如果列表为空,则返回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

使用 减少根据 Map 对象列表的条件获取 Min/Max 值的示例

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);

Another example to get Min/Max value using 减少 based on condition for a list of class objects

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干净,但它仍然是一种强大的方法来执行更灵活的操作。

int minF() {
final mass = [1, 2, 0, 3, 5];
mass.sort();
  

return mass[0];
}
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;
}

如果需要更复杂的 min/max,比如查找一个字段的 min/max 对象,或者使用比较谓词,可以使用 收集包裹中的 minBy()maxBy():

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)```