Search code examples
javaarrayssortingobjectalphabetical

How to sort array of objects in Java by alphabet


I have class Library

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;
  }

How to list books with authors' last names in alphabetical order?


Solution

  • First, you should have a Book class for individual books. Assuming your Library is a list of books you can then do it like this.

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

    Since no details were provided about the author name field it sorts on the entire field whether its first, last or both names.

    If you want to sort them in place, a cleaner approach would be.

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