【问题标题】:Dart List min/max value飞镖列表最小值/最大值
【发布时间】:2013-12-27 18:10:35
【问题描述】:

如何在 Dart 中获取 List 的最小值和最大值。

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

我确定我可以 a) 编写一个简短的函数或 b) 复制然后对列表进行排序并选择最后一个值,

但我正在寻找是否有更原生的解决方案。

【问题讨论】:

    标签: dart


    【解决方案1】:
    int minF() {
      final mass = [1, 2, 0, 3, 5];
      mass.sort();
      
      return mass[0];
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        根据地图对象列表的条件使用 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);
        

        另一个使用 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);
        

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            【解决方案5】:

            假设列表不为空,您可以使用Iterable.reduce

            import 'dart:math';
            
            main(){
              print([1,2,8,6].reduce(max)); // 8
              print([1,2,8,6].reduce(min)); // 1
            }
            

            【讨论】:

            • 列表可以为空怎么办?有没有办法避免检查空虚?
            • 你可以做[maxOnEmpty, ...list].reduce(max)
            • 谢谢,但我已经找到了更清洁的解决方案。 [1,2,8,6].fold(0, max) 会成功的。
            • 似乎这仍然不适用于空列表...例如[].fold(0, max) 引发错误。 @AlexSemeniuk
            • @PROgram52bc 您是否正确指定了列表类型?
            【解决方案6】:

            您现在可以使用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);
            }
            

            【讨论】:

              【解决方案7】:

              如果您不想导入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
              }
              

              【讨论】:

              • 为什么人们会非常喜欢这种方法?
              • @MateusFelipe 您可以将其作为函数传递,与 math.max 或 min 一样,我遇到了一些麻烦。
              • 那么,提供您的方法的特定用例是个好主意,因为它似乎是一个非常边缘的案例。
              • 这实际上是一个有用的评论。只要列表是对象列表而不是(字符串,数字)列表,我们就不能直接使用 dart:math。我们必须做一些类似“curr.id
              • 没错,它非常有用。例如,我将它用于 DateTime:dates.reduce((current, next) =&gt; current.compareTo(next) &gt; 0 ? current : next) 最接近 LINQ 类语法。
              猜你喜欢
              • 2021-07-12
              • 2020-02-11
              • 2018-10-29
              • 1970-01-01
              • 2016-09-04
              • 2018-03-05
              • 2023-03-29
              • 1970-01-01
              • 2022-11-14
              相关资源
              最近更新 更多