Home > Java > javaTutorial > How to Sort an Array of Objects by Name in Java?

How to Sort an Array of Objects by Name in Java?

Barbara Streisand
Release: 2024-11-25 12:17:12
Original
694 people have browsed it

How to Sort an Array of Objects by Name in Java?

Sorting Arrays of Objects in Java

Problem:

You have an array of objects that do not contain strings but instead have object references. Each object reference provides information about name, ID, author, and publisher through a toString method. The task is to sort this array by the name field. However, you are uncertain how to extract the name from each object and use it as the sorting criteria.

Solution:

To extract the name from each object and sort by this field, you can use the following approach:

List<Book> books = new ArrayList<Book>();

Collections.sort(books, new Comparator<Book>() {
  @Override
  public int compare(Book o1, Book o2) {
    return o1.getName().compareTo(o2.getName());
  }
});
Copy after login

In this example:

  • List is a list representing your array of objects.
  • Collections.sort is used to sort the list.
  • new Comparator() {...} defines a custom comparator to determine the sorting order.
  • o1.getName() extracts the name field from the first object using the getter method or direct access if the field is public.
  • o2.getName() extracts the name field from the second object.
  • compareTo compares the extracted names, returning a negative value if the first name is smaller, a positive value if it's larger, and zero if they are equal.

The above is the detailed content of How to Sort an Array of Objects by Name in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template