I have a class which contain called books which contains 3 variables.
String name;
int price;
int pages;
I need to sort these but cannot use the compare To interface on the book class. Is there a way to sort by name then price then pages?
I have a class which contain called books which contains 3 variables.
String name;
int price;
int pages;
I need to sort these but cannot use the compare To interface on the book class. Is there a way to sort by name then price then pages?
// create a class for comparing name that implements the comparator interface
class BooknameComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
return s1.name.compareTo(s2.name);
}
}
// create a class for comparing price
class PriceComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.price==s2.price)
return 0;
else if(s1.price>s2.price)
return 1;
else
return -1;
}
}
In your main class ,call the sort method as follows :
// for comparison using name
Collections.sort(al,new BooknameComparator ());
// for comaprison using price
Collections.sort(al,new PriceComparator ());
You can customise your sorting based on your needs and these classes
The answer from Vishsh is the solution to your problem - you don't need to modify the Book class in order to create a comparator based on its fields. I 'll just show the Java 8 syntax for doing this (which is more concise).
Edit
This is how you would sort your books if they were contained in a list:
Collections.sort(bookArray,Comparator.comparing(Book::getName));
Collections.sort(bookArray,Comparator.comparing(Book::getPrice));
Collections.sort(bookArray, Comparator.comparing(Book::getPages));
Now that you have an array, you can use:
Book[] sortedBookArray = Arrays.stream(bookArray).sorted(Comparator.comparing(Book::getPrice)).sorted(Comparator.comparing(Book::getName)).sorted(Comparator.comparing(Book::getPrice)).toArray();