Provide minWith and maxWith to find maximum and minimum values according to the given comparator.
#KT-9002 Fixed
This commit is contained in:
@@ -1436,6 +1436,20 @@ public inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R):
|
||||
return maxElem
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first element having the largest value according to the provided [comparator] or `null` if there are no elements.
|
||||
*/
|
||||
public fun <T> Iterable<T>.maxWith(comparator: Comparator<in T>): T? {
|
||||
val iterator = iterator()
|
||||
if (!iterator.hasNext()) return null
|
||||
var max = iterator.next()
|
||||
while (iterator.hasNext()) {
|
||||
val e = iterator.next()
|
||||
if (comparator.compare(max, e) < 0) max = e
|
||||
}
|
||||
return max
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the smallest element or `null` if there are no elements.
|
||||
*/
|
||||
@@ -1469,6 +1483,20 @@ public inline fun <T, R : Comparable<R>> Iterable<T>.minBy(selector: (T) -> R):
|
||||
return minElem
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first element having the smallest value according to the provided [comparator] or `null` if there are no elements.
|
||||
*/
|
||||
public fun <T> Iterable<T>.minWith(comparator: Comparator<in T>): T? {
|
||||
val iterator = iterator()
|
||||
if (!iterator.hasNext()) return null
|
||||
var min = iterator.next()
|
||||
while (iterator.hasNext()) {
|
||||
val e = iterator.next()
|
||||
if (comparator.compare(min, e) > 0) min = e
|
||||
}
|
||||
return min
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` if the collection has no elements.
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user