R
Rishtaara
Java Fundamentals
Lesson 34 of 36Article17 min

Lambda & Advanced Sorting

Lambda syntax: (params) -> expression or { statements }. Used with functional interfaces.

Lambda — short anonymous functions

Lambda syntax: (params) -> expression or { statements }. Used with functional interfaces.

Replaces verbose anonymous classes for simple callbacks.

Real-life example: Lambda is a quick note instead of full letter — "(x) -> x * 2" says double the number, nothing more.

Lambda expressions
import java.util.*;

List<String> names = new ArrayList<>(List.of("Rohan", "Asha", "Priya"));
names.sort((a, b) -> a.compareTo(b));
names.forEach(name -> System.out.println(name));

Advanced Sorting — Comparator and streams

Comparator.comparing(Person::getName) sorts objects by field. thenComparing chains rules.

Streams: list.stream().sorted().filter().map() — declarative pipeline.

Real-life example: Advanced sorting is ranking students — first by grade, then by name if grades tie.

Comparator and stream sort
import java.util.*;

record Student(String name, int marks) {}

List<Student> students = List.of(
    new Student("Asha", 90),
    new Student("Rohan", 85)
);

students.stream()
    .sorted(Comparator.comparingInt(Student::marks).reversed())
    .forEach(s -> System.out.println(s.name() + " " + s.marks()));