Posts

Comparator - Java 8

Image
 Comparator interface now have multiple functions which will helps us to have multiple comparison together. see below Comparator.comparing() : static method which takes comparator to compare thenComparaing(): use it when you want to have another comparator to compare thenComparingInt, thenComparingDouble, thenComparingLong : specialized for primitive types. Example:    In the given example we have made flexibility to sort the employee List by firstName, lastName or Salary and sorting order can be asc/desc import java.math.BigDecimal; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class ComparatorTest { public static void main(String[] args) { ArrayList<Employee> employees = getUnsortedEmployeeList (); //Compare by first name and then last name Comparator<Employee> compareByName = getCompareBy ( "salary" ); System. out .println( getSortedLis