Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin way of filtering max values from 2 arrays?

Tags:

arrays

kotlin

I currently have 2 arrays, both containing 5 objects. All objects contain Int variables.

Sample data:

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 = ??

What I'm trying to do is create a function which will filter these arrays on the maximum values. Now I know Kotlin has a method on their array called max() which will return the maximum value of the array it is used on.

This made me wonder (currently I'm using nested for-loop just like someone would in Java.), is there a visually beautiful faster/better way of doing so in Kotlin?

Expected output using sample data:

array3[22,17,16,15,12]
like image 919
Ivar Reukers Avatar asked Oct 25 '16 12:10

Ivar Reukers


1 Answers

You would like to have the 5 bigger int of the two arrays?

(array1 + array2).sortedArrayDescending().take(5)
// [22, 17, 16, 15, 12]

With edited answer:

(array1 + array2).sortedByDescending { it.number }.take(5)
// [Demo(number=22, name=j), Demo(number=17, name=e), Demo(number=16, name=i), Demo(number=15, name=h), Demo(number=12, name=a)]

http://try.kotlinlang.org/#/UserProjects/6eu172fogobv6na0mtafc9k9ol/klp8i0ttl32ip1q8ph3lk0s9bn

like image 85
Kevin Robatel Avatar answered Nov 09 '22 21:11

Kevin Robatel