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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With