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

Colton Idle

03/30/2023, 11:43 PM
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

ephemient

03/30/2023, 11:50 PM
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

Colton Idle

03/31/2023, 12:28 AM
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

nkiesel

03/31/2023, 11:17 PM
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

ephemient

03/31/2023, 11:24 PM
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

nkiesel

03/31/2023, 11:28 PM
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

ephemient

03/31/2023, 11:29 PM
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

nkiesel

03/31/2023, 11:37 PM
Copy code
if (ids.sorted() == books.map(Book::id).sorted()) books.sortedBy { ids.indexOf(it.id) } else books.shuffled()
🙂
e

ephemient

03/31/2023, 11:38 PM
of course there's the classic
Copy code
while (ids != books.map(Book::id)) books.shuffle()
😆
😆 1
n

nkiesel

03/31/2023, 11:39 PM
(it's Friday, after all...)
that's a good one as well
we need an Easter of Code!
c

Colton Idle

04/01/2023, 7:45 PM
lmao. Thanks all for teaching!
4 Views