If I have a list of [1, 7, 5] and then a separate ...
# getting-started
c
If I have a list of [1, 7, 5] and then a separate List<Book> and book has a property called id. How do I sort this list of books in the same order of my original list?
e
do you mean
Copy code
val booksById = books.associateBy { it.id }
ids.map { booksById[it] }
or
Copy code
books.sortedWith(compareBy(compareBy(ids::indexOf), Book::id))
?
c
so the firstList should be thought of as sortOrderList, and the second list is just random order books, that have an id. I think the second one is what i want. let me try when i get home!
Yep, the mapper variant worked for me. Hadn't thought about that route. thanks @ephemient
n
I though you asked for
Copy code
data class Book(val id: Int, val title: String)
val lb = listOf(Book(5, "Five"), Book(1, "One"), Book(7, "Seven"))
val li = listOf(1, 7, 5)
lb.sortedBy { li.indexOf(it.id) }
e
oh right, I was originally writing
compareBy(compareBy(ids::indexOf, naturalOrder()), Book::id)
, but then I decided that keeping the original for unspecified items was probably a better choice, in which case
sortedBy
is sufficient
if the list of IDs contains all the IDs, and all the IDs are unique, then all the methods here return the same value. but if the list of IDs is a subset, then the results are different
n
yeah, right. I assumed that the id list is just a re-ordered list of ids of the books list. If not, then all the corner cases become important to handle, and we would need more info on requirements.
e
Copy code
data class Book(val id: Int)
val ids = listOf(0, 2, 4)
val books = List(5) { Book(5 - it) }

ids.map(books.associateBy { it.id }::get) // => [null, Book(2), Book(4)]
books.sortedBy { ids.indexOf(it.id) } // => [Book(5), Book(3), Book(1), Book(2), Book(4)]
books.sortedBy { ids.indexOf(it.id) + Int.MIN_VALUE } // => [Book(2), Book(4), Book(5), Book(3), Book(1)]
n
Copy code
if (ids.sorted() == books.map(Book::id).sorted()) books.sortedBy { ids.indexOf(it.id) } else books.shuffled()
🙂
e
of course there's the classic
Copy code
while (ids != books.map(Book::id)) books.shuffle()
😆
😆 1
n
(it's Friday, after all...)
that's a good one as well
we need an Easter of Code!
c
lmao. Thanks all for teaching!