Sort collection by object property in Java

A lot of time, we are sorting something in our applications. Sort numbers, sort string, etc. What about when we are sorting objects with their property. For example, you have a person class and you have a list of persons. And you need to sort this list by age property of person.

There is a lot of samples on developer forums about sorting for different programming languages. I want to show, how can you do this by Comparator in a few lines of code.

Let's go.

We have a Person class :
public class Person {
    public String FirstName;
    public String LastName;
    public Integer Age;
}
And have a person list :
    List<Person> persons;
How to sort persons list by age property ?
Collections.sort(persons, new Comparator<Person>() {
    public int compare(Person p1, Person p2) {
        return p1.Age.compareTo(p2.Age);
    }
});
That's all. You have sorted persons list.

2 comments:

zanobijadea said...

Casino Near Denver | Mapyro
Discover the best 제천 출장안마 casinos near 오산 출장안마 Boulder, Colorado near Snoqualmie Casino & 거제 출장마사지 Hotel. 원주 출장샵 Explore reviews, ratings and information for 김포 출장안마 the Boulder area. Nearby places

Nabeekook said...

Great explanation on sorting collections by object properties in Java! Understanding these techniques is essential for efficient data handling and application performance. For those looking to expand their expertise in secure coding and IT security, enrolling in Cyber Security Training in Chennai can be a valuable step toward mastering cybersecurity fundamentals.

Post a Comment