1

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);
}
user9480
  • 324
  • 1
  • 13

4 Answers4

3

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());
Siva
  • 1,938
  • 1
  • 17
  • 36
0

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());
sidgate
  • 14,650
  • 11
  • 68
  • 119
0

Write your own Comparator by implementing Compareable

Refer this How to compare objects by multiple fields

Community
  • 1
  • 1
Dipika
  • 584
  • 2
  • 12
0

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()); 
Shekhar Khairnar
  • 2,643
  • 3
  • 26
  • 44