You have a list of books, each of which is represented by a Book class object containing the title, author, and price fields. You need to sort this list of books by price in ascending order.
Comparable and Comparator
Which book is cheaper?
Report a typo
Sample Input 1:
Sample Output 1:
1984 - George Orwell - 8.99
The Catcher in the Rye - J.D. Salinger - 9.99
To Kill a Mockingbird - Harper Lee - 10.99
The Great Gatsby - F. Scott Fitzgerald - 12.99Write a program in Kotlin
class Book(val title: String, val author: String, val price: Double)
fun main() {
val books = listOf(
Book("The Great Gatsby", "F. Scott Fitzgerald", 12.99),
Book("To Kill a Mockingbird", "Harper Lee", 10.99),
Book("1984", "George Orwell", 8.99),
Book("The Catcher in the Rye", "J.D. Salinger", 9.99)
)
val sortedBooks = books.sortedWith(Comparator {
// put your code here
})
sortedBooks.forEach { println("${it.title} - ${it.author} - ${it.price}") }
}
___
By continuing, you agree to the JetBrains Academy Terms of Service as well as Hyperskill Terms of Service and Privacy Policy.
Create a free account to access the full topic
By continuing, you agree to the JetBrains Academy Terms of Service as well as Hyperskill Terms of Service and Privacy Policy.