public class Publication {
private String name;
private String author;
private int price;
private String language;}
public class Book extends Publication {
private int ISBN;
public Book(String name, String author, String language, int price, int ISBN) {
super(name, author, language, price);
this.ISBN = ISBN;
}
.
public class Book extends Publication {
private int ISBN;
public Book(String name, String author, String language, int price, int ISBN) {
super(name, author, language, price);
this.ISBN = ISBN;
}
consider these classes
In another class I made an arraylist of Book
class
now I want to sort and print this arraylist based on name
and then author
but I don't know what can I do
CodePudding user response:
List<Book> books = new ArrayList<>();
//put elements in your list
books.sort((b1,b2) ->{
int comparator;
if (b1.name==b2.name){
comparator = b1.author.compareTo(b2.author);
} else {
comparator = b1.name.compareTo(b2.name);
}
return comparator;
});
in list.short((b1,b2)); is how b1 is the current "Book", and b2 is the next "Book" in the list, the return value defines whether b1 is before or after b2;
b1 and b2 are variables of type Book, you can change their name.
note: the String.compareTo() method; sorts alphabetically, but prioritizes uppercase letters, example: it will sort uppercase "Z" before lowercase "a".