Dart List min/max value

前端 未结 5 495
清歌不尽
清歌不尽 2021-02-01 12:12

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         


        
相关标签:
5条回答
  • 2021-02-01 12:27

    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
    }
    
    0 讨论(0)
  • 2021-02-01 12:28

    Using fold method with dart:math library

    Example:

    // Main function 
    void main() { 
      // Creating a geek list 
      var geekList = [121, 12, 33, 14, 3]; 
        
      // Declaring and assigning 
      // the largestGeekValue and smallestGeekValue 
      // Finding the smallest and 
      // largest value in the list 
      var smallestGeekValue = geekList.fold(geekList[0],min); 
      var largestGeekValue = geekList.fold(geekList[0],max); 
      
      // Printing the values 
      print("Smallest value in the list : $smallestGeekValue"); 
      print("Largest value in the list : $largestGeekValue"); 
    }
    

    Output:

    Smallest value in the list : 3
    Largest value in the list : 121
    

    Answer from : https://www.geeksforgeeks.org/dart-finding-minimum-and-maximum-value-in-a-list/

    0 讨论(0)
  • 2021-02-01 12:41

    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
    }
    
    0 讨论(0)
  • 2021-02-01 12:41

    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);
    }
    
    0 讨论(0)
  • 2021-02-01 12:42

    For empty lists: This will return 0 if list is empty, the max value otherwise.

      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
    
    0 讨论(0)
提交回复
热议问题