maxBy<K extends Comparable> method
T?
maxBy<K extends Comparable>(
- K selector(
- T element
Returns the element that yields the highest value based on the given selector
.
If the iterable is empty or all elements are null
, it returns null
.
The selector
function is used to extract a comparable key from each element.
The element with the highest value based on the selector is returned.
Example:
Iterable<int?>? numbers = [3, 5, 7, 2, null, 4];
int? result = numbers.maxBy((num) => num!); // 7
Example with a custom object:
class Product {
final String name;
final double price;
Product(this.name, this.price);
}
Iterable<Product?>? products = [
Product('Apple', 1.5),
Product('Banana', 0.8),
Product('Mango', 2.0),
null
];
Product? result = products.maxBy((product) => product?.price ?? 0.0);
print(result?.name); // Mango
Implementation
T? maxBy<K extends Comparable>(K Function(T element) selector) {
if (isEmpty) return null;
T? maxElement;
K? maxKey;
for (final element in whereType<T>()) {
// Filters out nulls
final key = selector(element);
if (maxKey == null || key.compareTo(maxKey) > 0) {
maxElement = element;
maxKey = key;
}
}
return maxElement;
}