Explain Codes LogoExplain Codes Logo

How to sort List of objects by some property

java
comparator
sorting
java-8
Nikita BarsukovbyNikita Barsukov·Nov 18, 2024
TLDR

Java 8 Comparator is used to sort a List by a property. Given a List of Person objects, sorted them by age:

List<Person> people = ...; people.sort(Comparator.comparing(Person::getAge)); // Sort by ascending age

For descending order:

people.sort(Comparator.comparing(Person::getAge).reversed()); // Reverse the age, like a youth potion!

Comparator : The sorting wizard!

Comparator lets you define your own sorting mechanics. For multiple field sorting, use its magic spell: thenComparing!

people.sort(Comparator.comparing(Person::getLastName).thenComparing(Person::getFirstName));

Handling null values with grace, not the kind NullPointerException appreciates:

people.sort(Comparator.comparing(Person::getAge, Comparator.nullsFirst(Integer::compareTo)));

Performance matters in sorting. Specific comparison methods are available for primitive types like int:

people.sort(Comparator.comparingInt(Person::getAge)); // Sorting so fast, you'd think it's in a hurry!

Safety first! Avoid ClassCastException by ensuring the property types. This ain't a magic trick!

Custom comparison: For when you're feeling fancy

Override compare method in Comparator interface to define custom sorting logic:

people.sort(new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { // Return your own comparison logic. This isn't a Hobbit movie, shorter is better. return p1.getBirthday().compareTo(p2.getBirthday()); } }); // A custom sorting adventure!

Got a nifty little Comparator? Save it as static final variables for use whenever, wherever. It's the little sorting helper!

Lambdas, not the Greek letter

Use lambdas, because sometimes even Java likes to go to the "Modern Art" gallery of coding:

people.sort((p1, p2) -> p1.getAge() - p2.getAge());

Sorting all the things

The natural order: Survival of the sorted

Classes with a natural order more powerful than gravity, implement the Comparable interface:

class Person implements Comparable<Person> { // The good stuff: members and other methods... @Override public int compareTo(Person other) { return Integer.compare(this.age, other.age); } } Collections.sort(people); // *Poof!* Sorted list!

Fancy level-up: Advanced multi-field sorting

Create a series of comparators for multi-level sorting:

Comparator<Person> byHeight = Comparator.comparing(Person::getHeight); Comparator<Person> byWeight = Comparator.comparing(Person::getWeight); people.sort(byHeight.thenComparing(byWeight)); // *Poof!* Multi-sorted list!

When life gives you Streams

Comparator can make Streams sorted():

List<Person> sortedList = people.stream() .sorted(Comparator.comparing(Person::getAge)) .collect(Collectors.toList()); // Sorting with style!

Avoid the sorting banana peels

Keep an eye out for common traps:

  • Cast exceptions: Comparing an apple and an orange? Be mindful of property types.
  • Null values: Designate a corner for them with Comparator.nullsFirst() or Comparator.nullsLast(). Kick nulls to the curb!
  • Performance: Performance art? Nah, high-performing codes with specialized methods like comparingInt.