java - 使用字段对类的 Arraylist 进行排序

标签 java class inheritance arraylist

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/

相关文章:

java - 为什么我的 3D 立方体在旋转时会变形?

Scala抽象类,self做什么?

php - 为什么PHP在访问对象属性时不需要$?

swift:如何将父类(super class)中的公共(public)方法覆盖为子类中的私有(private)方法

python - 继承和扩展 Python bytearray

python - 访问派生类中已更改的基类实例属性

java - 如何在 Eclipse 中手动安装 EGit 插件

java - 如何在 Spring-WS 中向响应负载添加附件?

无效方法的Java单元测试

Java:当我实例化抽象类的子类时,它无法识别其父类(super class)的构造函数