I have a list of people and each person has a TYPE...
# getting-started
c
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
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
partition hm. Haven't heard of that.
is partition faster than n log n
e
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
Interesting. Do the docs have these O(n) runtimes called out or is this just something you knonw?
e
unlike C++, the docs to not commit to any particular complexity, no
c
Cool. I'll take your word for it then. 😄
u
implement a normal comparator