Dart List最小/最大值

bas*_*eps 31 dart

如何获得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)

  • 谢谢,但我已经找到了更清洁的解决方案。`[1,2,8,6].fold(0, max)` 就可以了。 (8认同)
  • 您可以执行“[maxOnEmpty, ...list].reduce(max)”。 (3认同)

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)

  • 这实际上是一个有用的评论。每当列表是对象列表而不是(字符串,数字)列表时,我们就不能直接使用 dart:math。我们必须做一些类似“curr.id &lt; next.id”等的事情。 (16认同)

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)


呂學洲*_*呂學洲 7

如果您的列表为空,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获取最小值/最大值更干净,但它仍然是执行更灵活操作的强大方法。