Sunday, November 24, 2024

Sorting a List of Objects in Java 8 Using Lambda and Comparator

 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:

  1. Alphabetically by name.
  2. Numerically by age.
  3. Combined sorting by name and age.

The Person Class

Here’s our sample class:


public 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; } @Override public String toString() { return "Person{name='" + name + "', age=" + age + '}'; } }

Sample Data

To demonstrate sorting, we’ll create a list of Person objects:


import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<Person> people = Arrays.asList( new Person("Alice", 24), new Person("Bob", 30), new Person("Charlie", 22), new Person("Alice", 28) ); // Sorting examples below } }

Sorting by Name

To sort alphabetically by name:


people.sort((p1, p2) -> p1.getName().compareTo(p2.getName()));

Or using Comparator.comparing:


people.sort(Comparator.comparing(Person::getName));

Output:


[Person{name='Alice', age=24}, Person{name='Alice', age=28}, Person{name='Bob', age=30}, Person{name='Charlie', age=22}]

Sorting by Age

To sort by age:


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

Or with Comparator.comparingInt:


people.sort(Comparator.comparingInt(Person::getAge));

Output:


[Person{name='Charlie', age=22}, Person{name='Alice', age=24}, Person{name='Alice', age=28}, Person{name='Bob', age=30}]

Sorting by Name and Age

To combine sorting criteria, we can chain comparators:


people.sort(Comparator.comparing(Person::getName).thenComparing(Person::getAge));

Output:


[Person{name='Alice', age=24}, Person{name='Alice', age=28}, Person{name='Bob', age=30}, Person{name='Charlie', age=22}]

Reversing the Sort Order

If you want descending order, use reversed():


people.sort(Comparator.comparing(Person::getName).reversed());

Or for combined criteria:


people.sort(Comparator.comparing(Person::getName) .thenComparing(Person::getAge) .reversed());

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

Understanding Essential DNS Record Types for Web Administrators

  Understanding Essential DNS Record Types for Web Administrators Introduction The Domain Name System (DNS) acts as the backbone of the inte...