Sort ArrayList of custom Objects by property
To sort an ArrayList of custom objects by a property, you can use the Collections.sort
method and pass it a custom Comparator
.
Here's an example of how you can do this:
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
});
In this example, the Person
class has a getAge
method that returns the age of the person. The Comparator
compares the ages of two Person
objects and returns a negative number if the first person is younger, a positive number if the first person is older, and 0 if the ages are the same.
This will sort the people
list in ascending order by age. To sort the list in descending order, you can reverse the comparison by swapping the order of the operands:
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p2.getAge() - p1.getAge();
}
});
Alternatively, you can use the sort
method of the List
interface and pass it a Comparator
as an argument:
people.sort(new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
});
This will sort the people
list in ascending order by age.
Note that the sort
method uses a modified merge sort algorithm, which has a time complexity of O(n * log(n)). This means that it is efficient for sorting large lists.