Java Book Class: Sorting and Displaying Books by Price

Classified in Technology

Written at on English with a size of 1.89 KB.

Java Book Class Example

Sorting and Displaying Books by Price

This code defines a simple Book class in Java and demonstrates how to sort and display a list of books by price in ascending order.

Book Class

The Book class has the following attributes:

  • bookId: Unique identifier for each book.
  • title: Title of the book.
  • author: Author of the book.
  • publisher: Publisher of the book.
  • price: Price of the book.

The class provides a constructor to initialize these attributes, getters to access them, setters to modify them, and a toString() method to represent a Book object as a string.

Program3 Class

The Program3 class contains the main method, which performs the following actions:

  1. Creates a list of Book objects.
  2. Adds several book instances to the list.
  3. Sorts the bookList using Collections.sort() and a lambda expression to compare books based on their prices.
  4. Prints the sorted list of books to the console.

Code Explanation

The key part of the code is the sorting logic using Collections.sort() and a lambda expression. The lambda expression (bookA, bookB) -> Double.compare(bookA.getPrice(), bookB.getPrice()) defines a custom comparator that compares two Book objects based on their price attribute. This ensures that the books are sorted in ascending order of their prices.

This example demonstrates a simple way to sort and display a list of objects in Java based on a specific attribute. You can modify the code to sort based on other attributes or in descending order by changing the comparison logic in the lambda expression.

Entradas relacionadas: