Java 8 Streams Sorting with Comparable and Comparator

🚀 Comparable vs Comparator in Java 8 (with Streams Examples) Sorting is one of the most common operations in real-world applications. In Java, we use Comparable and Comparator — and with Java 8 Streams, sorting became even more powerful and readable. Let’s break it down 👇 🔹 1️⃣ Comparable (Natural Ordering) Used when a class defines its own default sorting logic. class Employee implements Comparable<Employee> { private int salary; @Override public int compareTo(Employee other) { return this.salary - other.salary; // natural order } } Usage with Streams: employees.stream() .sorted() .forEach(System.out::println); 👉 Best when sorting logic is fixed and always the same. 🔹 2️⃣ Comparator (Custom Ordering) Used when sorting logic is external or multiple sorting strategies are required. employees.stream() .sorted(Comparator.comparing(Employee::getName)) .forEach(System.out::println); 🔹 3️⃣ Reverse Sorting employees.stream() .sorted(Comparator.comparing(Employee::getSalary).reversed()) .forEach(System.out::println); 🔹 4️⃣ Multiple Field Sorting (Then Comparing) employees.stream() .sorted(Comparator.comparing(Employee::getDepartment) .thenComparing(Employee::getSalary)) .forEach(System.out::println); 🔹 5️⃣ Null Safe Sorting employees.stream() .sorted(Comparator.comparing( Employee::getName, Comparator.nullsLast(String::compareTo) )) .forEach(System.out::println); 🔥 Key Differences ✔ Comparable → Inside the class ✔ Comparator → Outside the class ✔ Comparable → Single natural order ✔ Comparator → Multiple custom sorting logics ✔ Java 8 → Lambda + Method Reference makes Comparator extremely powerful. #Java #Java8 #Streams #Comparator #Comparable #BackendDevelopment #SoftwareEngineering

To view or add a comment, sign in

Explore content categories