Java program to sort arraylist of custom objects by property
To sort an ArrayList
of custom objects by a particular property, you can use the Collections.sort()
method along with a custom Comparator
class. The Comparator
class will define how the objects should be compared and sorted.
Here is an example Java program that demonstrates how to sort an ArrayList
of Person
objects by their age property:
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class SortArrayListOfObjects { public static void main(String[] args) { // Create an ArrayList of Person objects ArrayList<Person> people = new ArrayList<Person>(); people.add(new Person("John", 25)); people.add(new Person("Sarah", 30)); people.add(new Person("Bob", 20)); // Sort the ArrayList by age using a custom Comparator Collections.sort(people, new Comparator<Person>() { public int compare(Person p1, Person p2) { return p1.getAge() - p2.getAge(); } }); // Print the sorted list of people for (Person person : people) { System.out.println(person.getName() + " (" + person.getAge() + ")"); } } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
In this program, we first create an ArrayList
of Person
objects, with each person having a name and an age. We then sort the ArrayList
using the Collections.sort()
method, passing in a custom Comparator
that compares Person
objects by their age using the getAge()
method. The compare()
method of the Comparator
subtracts the age of the second person from the age of the first person, resulting in a negative number if the first person is younger than the second person, a positive number if the first person is older than the second person, and zero if they have the same age. This Comparator
is used to sort the ArrayList
in ascending order by age.
Finally, we print the sorted list of people to the console. When you run this program, the output should be:
Bob (20) John (25) Sarah (30)