Approach 1 — Using Comparator.comparing
List<Employee> sorted = employees.stream() .sorted(Comparator.comparing(Employee::getName)) .collect(Collectors.toList());
Approach 2 — Using a Lambda Comparator
List<Employee> sorted2 = employees.stream() .sorted((a, b) -> a.getName().compareTo(b.getName())) .toList();
Explanation:
Comparator.comparing
is concise and readable.- Null-safe versions are available via
Comparator.nullsFirst
andnullsLast
.