Posts

Showing posts from July, 2017

Refactoring Comparators in Java 8

In this article, I will show how  we  can refactor our old ugly comparators to cool elegant one. Example Domain Class Employee { private int salary; private int yearsOfExperience; int getSalary() { return salary; } public int getYearsOfExperience() { return yearsOfExperience; } } Use Case Sort a list of  Employee  class by  salary ,  yearsOfExperience  etc. Java 7 Code Sorting By Salary employees.sort(new Comparator<Employee>() { @Override public int compare(Employee o1, Employee o2) { return o1.getSalary() - o2.getSalary(); } }); Sorting By Years of Experience employees.sort(new Comparator<Employee>() { @Override public int compare(Employee o1, Employee o2) { return o1.getSalary() - o2.getSalary(); } }); This code looks ugly. Actually, it became ugly after the introduction of lambda operator. Refactoring in Java 8 Java8  introduced a new operator