Home >Java >javaTutorial >How to Sort an ArrayList of Fruit Objects by Fruit Name in Java?
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!