Kotlin way to filter maximum values ​​from 2 arrays?

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

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 that will filter these arrays at maximum values. Now I know that Kotlin has a method in their array with a name max()that will return the maximum value of the array used.

This made me think (I am currently using a nested for-loop, like someone in Java.) Is there a visually beautiful faster / better way to do this in Kotlin?

Expected Result Using Sample Data:

array3[22,17,16,15,12]
+4
2

5 int ?

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

:

(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

+6

, :

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

(a + b) a b, .sortedDescending() . .take(5) , .toTypedArray() .


Demo Comparable<Demo>, :

  • Comparable<T> , .sortedDescending()

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

    .

  • .sortedByDescending { }, , :

     val c = (a + b).sortedByDescending { it.number }.take(5).toTypedArray()
    
  • , :

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

Source: https://habr.com/ru/post/1658823/


All Articles