如何按字母对 Java 中的对象数组进行排序

How to sort array of objects in Java by alphabet

我有class图书馆

public class Books extends Library {
  String regNumber
  String author;
  String name;
  int yearOfPublishing;
  String publishingHouse;
  int numberOfPages;

  public Books(String regNumber, String author, String name, int yearOfPublishing,
      String publishingHouse, int numberOfPages) {
    this.regNumber = regNumber;
    this.author = author;
    this.name = name;
    this.yearOfPublishing = yearOfPublishing;
    this.publishingHouse = publishingHouse;
    this.numberOfPages = numberOfPages;
  }

如何按作者姓氏的字母顺序列出书籍?

首先,您应该有一个 Book class 用于个人书籍。假设您的图书馆是一个图书列表,您可以这样做。

List<Book> sortedLibrary = library.stream()
                .sorted(Comparator.comparing(book -> book.author))
                .collect(Collectors.toList());

由于没有提供有关 author 名称字段的详细信息,因此它对整个字段进行排序,无论是名字、姓氏还是两者。

如果您想就地对它们进行排序,更简洁的方法是。

library.sort(Comparator.comparing(book->book.author));