Last active
July 5, 2019 01:00
-
-
Save soulduse/aeee3b330702d610bc8d9716adcdfafd to your computer and use it in GitHub Desktop.
How to sort based on/compare multiple values in Kotlin?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SortItem(bool=true, num=5, date=2019-07-05T00:57:12.256Z, name=A) | |
SortItem(bool=true, num=10, date=2019-07-05T00:59:12.258Z, name=C) | |
SortItem(bool=true, num=20, date=2019-07-05T00:59:12.258Z, name=D) | |
SortItem(bool=false, num=5, date=2019-07-05T00:57:12.258Z, name=E) | |
SortItem(bool=false, num=5, date=2019-07-05T00:58:12.258Z, name=B) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SortTest { | |
@Test | |
fun `sorting`() { | |
DUMMY.sortedWith( | |
compareByDescending<SortItem> { it.bool } | |
.thenBy { it.num } | |
.thenBy { it.date } | |
.thenBy { it.name } | |
).print() | |
} | |
private fun <T> List<T>.print() { | |
println(this.joinToString("\n")) | |
} | |
companion object { | |
private val DUMMY = arrayListOf( | |
SortItem(true, 5, Instant.now().plusSeconds(60), "A"), | |
SortItem(false, 5, Instant.now().plusSeconds(120), "B"), | |
SortItem(true, 10, Instant.now().plusSeconds(180), "C"), | |
SortItem(true, 20, Instant.now().plusSeconds(180), "D"), | |
SortItem(false, 5, Instant.now().plusSeconds(60), "E") | |
) | |
} | |
} | |
data class SortItem( | |
val bool: Boolean, | |
val num: Int, | |
val date: Instant, | |
val name: String | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment