Kotlin如何从2个数组中过滤出最大值?

5

我目前有2个数组,每个数组包含5个对象。所有对象都包含 Int 变量。

样例数据:

data class Demo(val number: Int, val name: String)

val a = Demo(12, "a")
val b = Demo(1, "b")
val c = Demo(3, "c")
val d = Demo(5, "d")
val e = Demo(17, "e")

val array1 = arrayOf(a,b,c,d,e)

val f = Demo(3, "f")
val g = Demo(8, "g")
val h = Demo(15, "h")
val i = Demo(16, "i")
val j = Demo(22, "j")

val array2 = arrayOf(f,g,h,i,j)

//val array3 = ??

我想要做的是创建一个函数,它将过滤这些数组中的最大值。现在我知道 Kotlin 的数组上有一个叫做 max() 的方法,它会返回所使用的数组的最大值。
这让我想到(目前我正在使用嵌套 for 循环,就像 Java 中的某人一样),在 Kotlin 中是否有更快/更好的方法来完成这个任务?
使用示例数据的预期输出:
array3[22,17,16,15,12]
2个回答

9

好的,但是如果这些值是包含两个值-数字名称的对象呢?(如果您想按 数字 排序)您会如何解决? - Ivar Reukers
1
你可以使用sortedByDescending来实现,例如(array1 + array2).sortedByDescending { it.number }.take(5) - Kevin Robatel
已经在sortedByDescending中编写了类似于when(it) {is Demo -> {it.number} is Demo2 -> {it.id} else null}的代码。 - Kevin Robatel
我想补充一点(至少根据给出的示例),array1.zip(array2) { l,r -> Math.max(l,r)}.sortedByDescending() 也是一个选项。 - Lovis
1
@Lovis 不对,你会得到一对中的最大值而不是所有数的最大值。让我们在这里尝试一下:http://try.kotlinlang.org/#/UserProjects/b81jsbes4qb6bd100pjipaoreg/59rotklqv5o7vds95lvrqs034n - Kevin Robatel
显示剩余4条评论

4

也许以下内容适合您的使用情况:

val c = (a + b).sortedDescending().take(5).toTypedArray()

在这里,(a + b)会创建一个包含ab内容的数组,接着.sortedDescending()将该数组从大到小排序并将结果放入列表中。然后你可以使用.take(5)筛选前五个元素,最后使用.toTypedArray()将其转换回数组。
如果您的类Demo没有实现Comparable<Demo>,您可以:
  • Implement Comparable<T> interface on that class to make .sortedDescending() applicable for it

    class Demo(...) : Comparable<Demo>{
        override fun compareTo(other: Demo): Int = number.compareTo(other.number)
    
        ...
    }
    

    Then just use the solution above.

  • Use .sortedByDescending { } to specify how the data should be compared:

     val c = (a + b).sortedByDescending { it.number }.take(5).toTypedArray()
    
  • Use comparators chain if you need comparison by multiple values:

     val c = (a + b)
             .sortedWith(compareBy<YourData> { it.number }.thenBy { it.name })
             .takeLast(5).reversed()
    

好的,但如果这些值是一个包含两个值(例如numbername)的对象,你该如何解决呢?(如果你想按number排序) - Ivar Reukers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接