Provide minWith and maxWith to find maximum and minimum values according to the given comparator.

#KT-9002 Fixed
This commit is contained in:
Ilya Gorbunov
2015-11-30 19:57:42 +03:00
parent b5e637bed5
commit 055c71e8d0
11 changed files with 433 additions and 1 deletions
@@ -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.
*/