Yes, absolutely! Sorting streams by custom object properties is one of the most common tasks in Java development. You do this by passing a Comparator to the sorted() method.
Imagine you have a User class:
class User {
String name;
int age;
User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}
You can sort a list of these users in several ways:
1. Sorting by a single property
Using Comparator.comparing(), you can tell Java which property to use for the sort:
List<User> users = Arrays.asList(
new User("Alice", 30),
new User("Bob", 20),
new User("Charlie", 25)
);
// Sort by Age (Ascending)
users.stream()
.sorted(Comparator.comparing(User::getAge))
.forEach(u -> System.out.println(u.getName()));
// Output: Bob, Charlie, Alice
2. Sorting in Reverse Order
You can simply chain .reversed() to the comparator:
// Sort by Age (Descending)
users.stream()
.sorted(Comparator.comparing(User::getAge).reversed())
.forEach(u -> System.out.println(u.getName()));
3. Sorting by Multiple Properties (Chaining)
If two objects have the same value for the first property, you can provide a "tie-breaker" using .thenComparing():
// Sort by Age, then by Name if ages are equal
users.stream()
.sorted(Comparator.comparing(User::getAge)
.thenComparing(User::getName))
.forEach(u -> System.out.println(u.getName()));
Why is this better?
Before Streams and Comparator.comparing, you would have to write complex logic inside a compare(o1, o2) method with multiple if-else blocks. This new way is declarative—you are telling Java what to sort by, rather than how to perform the comparison logic.
Labby's Tip: Always make sure your custom properties (like getAge) return types that are "Comparable" (like Integer, String, or Double). Most built-in Java types already are!