How to use fold method with dart:math library In Dart
The above code can be minimized importing the math libraries.
Example:
Dart
import "dart:math" ; // 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
Dart – Finding Minimum and Maximum Value in a List
In Dart we can find the minimum and maximum valued element present in the given list in seven ways:
- Using for loop to find the largest and smallest element.
- Using sort function to find the largest and smallest element.
- Using forEach loop to find the largest and smallest element.
- Using only reduce method in dart to find the largest and smallest element.
- Using reduce method with dart:math library.
- Using fold method with dart to find the largest and smallest element.
- Using fold method with dart:math library.
Using for loop
It is the most basic way to find the largest and smallest element present in the list by simply going through all the elements comparing them and giving the answer.
Example:
Dart
// Main function void main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Declaring and assigning the // largestGeekValue and smallestGeekValue var largestGeekValue = geekList[0]; var smallestGeekValue = geekList[0]; for (var i = 0; i < geekList.length; i++) { // Checking for largest value in the list if (geekList[i] > largestGeekValue) { largestGeekValue = geekList[i]; } // Checking for smallest value in the list if (geekList[i] < smallestGeekValue) { smallestGeekValue = geekList[i]; } } // 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
Using sort function
Dart also provides the user to sort the list in the ascending order i.e. first one is the smallest and last one is largest.
Example:
Dart
// Main function void main() { // Creating a geek list var geekList = [121, 12, 33, 14, 3]; // Sorting the list geekList.sort(); // Printing the values print( "Smallest value in the list : ${geekList.first}" ); print( "Largest value in the list : ${geekList.last}" ); } |
Output:
Smallest value in the list : 3 Largest value in the list : 121