


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); } }</fruit></fruit></fruit>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use