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;
}
考虑这些类
在另一个类中,我创建了 Book
类的数组列表
现在我想根据 name
排序并打印这个数组列表,然后根据 author
但我不知道我能做什么
最佳答案
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));就是b1是当前的“Book”,b2是列表中的下一个“Book”,返回值定义b1是在b2之前还是之后;
b1和b2是Book类型的变量,你可以更改它们的名称。
注意:String.compareTo() 方法;按字母顺序排序,但优先考虑大写字母,例如:它将大写“Z”排在小写“a”之前。
关于java - 使用字段对类的 Arraylist 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71790038/