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

How to Sort an ArrayList of Fruit Objects by Fruit Name in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-20 03:18:02564browse

How to Sort an ArrayList of Fruit Objects by Fruit Name in Java?

Sorting an ArrayList in Java Based on Fruit Name

Question:

How can you sort an ArrayList of Fruit objects based on their fruit names?

Implementation:

To sort an ArrayList of Fruit objects based on their fruit names, you can use a custom Comparator class. Here's how:

List<Fruit> fruits = new ArrayList<>();

Fruit fruit;
for (int i = 0; i < 100; i++) {
    fruit = new Fruit();
    fruit.setFruitName(...);
    fruits.add(fruit);
}

// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
    @Override
    public int compare(Fruit fruit2, Fruit fruit1) {
        return fruit1.getFruitName().compareTo(fruit2.getFruitName());
    }
});

This code uses a Comparator to compare two Fruit objects based on their fruit names. The compare method in the Comparator returns a negative value if fruit1 comes before fruit2 in alphabetical order, a positive value if fruit1 comes after fruit2, and 0 if they are equal. The Collections.sort method uses this Comparator to sort the ArrayList in ascending order of fruit names.

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

Statement:
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