Sorting a List of Objects in Java 8 Using Lambda and Comparator
Sorting collections is a common requirement in programming. With Java 8's introduction of lambda expressions and improvements to the Comparator
interface, sorting has become simpler and more elegant. This blog post will walk you through sorting a list of objects by string and integer attributes using these features.
Overview
We’ll create a class Person
with attributes name
(String) and age
(Integer). Then, we’ll sort a list of Person
objects:
- Alphabetically by name.
- Numerically by age.
- Combined sorting by name and age.
The Person
Class
Here’s our sample class:
Sample Data
To demonstrate sorting, we’ll create a list of Person
objects:
Sorting by Name
To sort alphabetically by name:
Or using Comparator.comparing
:
Output:
Sorting by Age
To sort by age:
Or with Comparator.comparingInt
:
Output:
Sorting by Name and Age
To combine sorting criteria, we can chain comparators:
Output:
Reversing the Sort Order
If you want descending order, use reversed()
:
Or for combined criteria:
Summary
Java 8’s lambda expressions and the improved Comparator
API make sorting clean and concise. By using Comparator.comparing
and thenComparing
, you can easily handle complex sorting logic in a readable way.
Key Points:
- Use lambdas for custom comparisons.
- Leverage
Comparator.comparing
for simple sorting. - Chain comparators for multi-level sorting.
Try these examples in your projects to simplify sorting logic!
No comments:
Post a Comment