Colton Idle
03/30/2023, 11:43 PMephemient
03/30/2023, 11:50 PMval booksById = books.associateBy { it.id }
ids.map { booksById[it] }
or
books.sortedWith(compareBy(compareBy(ids::indexOf), Book::id))
?Colton Idle
03/31/2023, 12:28 AMnkiesel
03/31/2023, 11:17 PMdata 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) }
ephemient
03/31/2023, 11:24 PMcompareBy(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 sufficientnkiesel
03/31/2023, 11:28 PMephemient
03/31/2023, 11:29 PMdata 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)]
nkiesel
03/31/2023, 11:37 PMif (ids.sorted() == books.map(Book::id).sorted()) books.sortedBy { ids.indexOf(it.id) } else books.shuffled()
šephemient
03/31/2023, 11:38 PMwhile (ids != books.map(Book::id)) books.shuffle()
šnkiesel
03/31/2023, 11:39 PMColton Idle
04/01/2023, 7:45 PM