标准二进制maxBy函数

问题描述 投票:2回答:2

我概括了以下代码:

fun max(that: Type): Type = if (this.rank() < that.rank()) that else this

对此:

fun max(that: Type): Type = maxBy(this, that) { it.rank() }

fun maxBy<T, U : Comparable<U>>(a: T, b: T, f: (T) -> U): T
    = if (f(a) < f(b)) b else a

在Kotlin的标准库中是否有类似maxBy的功能?我只能找到一个数组。

generics max comparable standard-library kotlin
2个回答
2
投票

Kotlin stdlib有maxmaxBy extension functions on Iterable

max的签名是:

fun <T : Comparable<T>> Iterable<T>.max(): T?

maxBy的签名是:

fun <T, R : Comparable<R>> Iterable<T>.maxBy(
    selector: (T) -> R
): T?

要么具有可比价值。 maxBy使用lambda来创建与每个项目相当的值。

这是一个测试用例,显示了两者的作用:

@Test fun testSO30034197() {
    // max:
    val data = listOf(1, 5, 3, 9, 4)
    assertEquals(9, data.max())

    // maxBy:
    data class Person(val name: String, val age: Int)
    val people = listOf(Person("Felipe", 25), Person("Santiago", 10), Person("Davíd", 33))
    assertEquals(Person("Davíd", 33), people.maxBy { it.age })
}

另见:Kotlin API Reference


0
投票

自Kotlin 1.1以来实现这一目标的最简单方法是使用maxOf方法。

© www.soinside.com 2019 - 2024. All rights reserved.