Question
I need help with this Java question. Please provide the final code and output if possible. Part 4: Book Comparators Suppose we have the following
I need help with this Java question. Please provide the final code and output if possible.
Part 4: Book Comparators
Suppose we have the following Name and Book classes, which you should not modify: class Name {
private String first, last;
public Name(String first, String last) {
this.first = first;
this.last = last;
}
public String getFirst() {
return first;
}
public String getLast() {
return last;
}
@Override
public String toString() {
return first + " " + last;
}
}
class Book {
private String title;
private Name author;
private double rating;
private int publicationYear;
public Book(String title, Name author, double rating, int publicationYear) {
this.title = title;
this.author = author;
this.rating = rating;
this.publicationYear = publicationYear;
}
public String getTitle() {
return title;
}
public Name getAuthor() {
return author;
}
public double getRating() {
return rating;
}
public int getPublicationYear() {
return publicationYear;
}
@Override public String toString() {
return title + " " + author + " " + rating + " " + publicationYear;
}
}
Suppose we have a Book[] named books. For each of the following sorting orders, write the line(s) of code needed to sort the elements of books from lowest to highest.
1.) Ordered by publication year.
2.) Ordered by rating and then by publication year.
3.) Ordered by author last name and then by author first name.
4.) Ordered by rating, then by publication year, then by author last name, and then by author first name.
5.) Ordered by rating, then by publication year, then by author last name, then by author first name, and then by title.
Hint: Use Arrays.sort. Send it the array and a Comparator
Comparator
Comparator.comparing(Book::getPublicationYear)
.thenComparing(Book::getRating)
.thenComparing(b -> b.getAuthor().getLast());
You do not have to use Comparator.comparing and thenComparing, but doing so typically makes your code more concise and readable.
Additionally, repeat at least one of the above five sortings, now assuming that books is a List
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started