English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, vous apprendrez à trier une ArrayList d'objets personnalisés en fonction d'une propriété donnée en Java.
import java.util.*; public class CustomObject { private String customProperty; public CustomObject(String property) { this.customProperty = property; } public String getCustomProperty() { return this.customProperty; } public static void main(String[] args) { ArrayList<Customobject> list = new ArrayList<>(); list.add(new CustomObject("Z")); list.add(new CustomObject("A")); list.add(new CustomObject("B")); list.add(new CustomObject("X")); list.add(new CustomObject("Aa")); list.sort((o1, o2) -> o1.getCustomProperty().compareTo(o2.getCustomProperty())); for (CustomObject obj : list) { System.out.println(obj.getCustomProperty()); } } }
Lorsque le programme est exécuté, la sortie est :
A Aa B X Z
In the above program, we define a CustomObject class with a String attribute customProperty
We also added an initialization property constructor and a getter function getCustomProperty () that returns customProperty
In the main () method, we create an array list of custom objects list and use5objects have been initialized.
To sort the list by the given attribute, we use the list's sort () method. The sort () method accepts the list to be sorted (the final sorted list is also the same) and a comparator
In our example, the comparator is a lambda expression
from the list o1and o2to get two objects
use the compareTo () method to compare the customProperty of two objects
if o1attribute is greater than o2attribute, the last return is a positive number; if o1attribute is less than o2attribute, then the last return is a negative number; if equal, then return zero.
Based on this, the list (list) is sorted by the smallest attribute to the largest attribute and stored back into the list (list)