Home > Java > javaTutorial > How can I sort an ArrayList of custom objects in Java based on a specific property?

How can I sort an ArrayList of custom objects in Java based on a specific property?

Susan Sarandon
Release: 2024-11-20 13:18:13
Original
534 people have browsed it

How can I sort an ArrayList of custom objects in Java based on a specific property?

Sorting an ArrayList of Custom Objects in Java

To sort a list of custom objects in Java, such as an ArrayList of Fruit objects based on a specific property, you can use a Comparator. Here's an example:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class FruitSorter {
    private List<Fruit> fruits = new ArrayList<>();

    public void sortFruits() {
        // Create a Comparator to compare fruits based on their fruit name
        Comparator<Fruit> comparator = new Comparator<Fruit>() {
            @Override
            public int compare(Fruit fruit2, Fruit fruit1) {
                return fruit1.getFruitName().compareTo(fruit2.getFruitName());
            }
        };

        // Sort the fruits list using the Comparator
        Collections.sort(fruits, comparator);
    }
}
Copy after login

In the above example, the sortFruits() method utilizes a custom Comparator to sort the fruits list based on the fruitName property. You can initialize your ArrayList of Fruit objects as per your requirement and then call the sortFruits() method to sort the list according to the fruit names.

The above is the detailed content of How can I sort an ArrayList of custom objects in Java based on a specific property?. For more information, please follow other related articles on the PHP Chinese website!

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