Dart List min/max value

2020-05-22 07:08发布

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.

标签: dart
4条回答
兄弟一词,经得起流年.
2楼-- · 2020-05-22 07:10

You can now achieve this with 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);
}
查看更多
【Aperson】
3楼-- · 2020-05-22 07:13

Inefficient way:

var n = [9, -2, 5, 6, 3, 4, 0];
n.sort();
print('Max: ${n.last}');  // Max: 9
print('Min: ${n[0]}');  // Min: -2

Without importing the 'dart: math' library:

var n = [9, -2, 5, 6, 3, 4, 0];

int minN = n[0];
int maxN = n[0];
n.skip(1).forEach((b) {
  minN = minN.compareTo(b) >= 0 ? b : minN;
  maxN = maxN.compareTo(b) >= 0 ? maxN : b;

});
print('Max: $maxN');  // Max: 9
print('Min: $minN');  // Min: -2
查看更多
做个烂人
4楼-- · 2020-05-22 07:18

Assuming the list is not empty you can use Iterable.reduce :

import 'dart:math';

main(){
  print([1,2,8,6].reduce(max)); // 8
  print([1,2,8,6].reduce(min)); // 1
}
查看更多
混吃等死
5楼-- · 2020-05-22 07:20

If you don't want to import dart: math and still wants to use 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
}
查看更多
登录 后发表回答