Question

Here I' comparing but only the title of the book. But after that I want to compare it with the author and the book no. As I know there must be only one override method. So please help me on this.

@Override

public int compareTo(Book bk) {

return this.bookTitle.compareTo(bk.bookTitle);
}
Was it helpful?

Solution

You have to implement different comparators for different sorting types and pass them for Collections.Sort method. See Comparator

Class AuthorSort implements Comparator<Book>
{

   public int compare(Book b1, Book b2){
       // do comparision on Author
    }

}

Implements Book Number Sorting

Class BookNoSort implements Comparator<Book>
{

   public int compare(Book b1, Book b2){
       // do comparision on Book Number
    }

}

Call Sort method on Collections class and provide different implentation

Collections.sort(list, new BookNumberSort());
Collections.sort(list, new AuthorSort());

OTHER TIPS

Google Comparator

class BookAuthorComparator implements Comparator<Book>{
    public int compare(Book b1, Book b2){
        return b1.getAuthor().compareTo(b2.getAuthor());
    }
}

Collections.sort(bookList, new BookAuthorCompartor());

Write your own Comparator by implementing Compareable

Refer this How to compare objects by multiple fields

you could use anonymous inner class as:

Collections.sort(bookList, new Comparator<Book>() {
        @Override
        public int compare(Book b1, Book b2) {
            return b1.property.compare(b2.property);
        }
    });

if you want sorting to be performed on title or author just change

return b1.getTitle().compare(b2.getTitle()); 

or

return b1.getAuthor().compare(b2.getAuthor()); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top