https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Colton Idle

11/30/2021, 3:50 AM
I have a list of people and each person has a TYPE. Either DIRECTOR, PROFESSOR or STUDENT. How do I sort the list so that all students are listed after the DIRECTORS and PROFESSORS? As a first approach to this, I think it would just be easier to just have two identical lists. filter out the students from list 1. and then filter out prof and directors from list2 and add them together.
e

ephemient

11/30/2021, 3:57 AM
Copy code
list.sortedBy { it.type == STUDENT }
since
false < true
although that's O(n log n) and is probably not the right solution unless you're also performing other sorting anyway
if this is the only reorder that you want to do, then
Copy code
val (students, others) = list.partition { it.type == STUDENT }
others + students
is more or less your approach but built into stdlib
c

Colton Idle

11/30/2021, 4:03 AM
partition hm. Haven't heard of that.
is partition faster than n log n
e

ephemient

11/30/2021, 4:08 AM
O(n)
in theory, if you didn't need to preserve order, you could simply swap elements in place - that's what C++'s partition function does - but Kotlin's does the obvious thing of building two new lists and filling them in order
c

Colton Idle

11/30/2021, 4:12 AM
Interesting. Do the docs have these O(n) runtimes called out or is this just something you knonw?
e

ephemient

11/30/2021, 4:12 AM
unlike C++, the docs to not commit to any particular complexity, no
c

Colton Idle

11/30/2021, 4:13 AM
Cool. I'll take your word for it then. 😄
u

ursus

11/30/2021, 8:40 PM
implement a normal comparator
2 Views