21
Jan

Comparator.comparing and Comparator.thenComparing

Chained comparators with Java8
================================

step 1. custom class whose objects needs to be sorted:
=======================================================

	Class Student
	{
	  private String name, jobtitle;
	  private int age, salary;

	  public Student(String, String, int, int);
	  Getters and Setters;
	  toString Override;
	}


Step 2: Chained comparators:
=============================

List<Student> studentsList = new ArrayList<Student>();

Collections.sort(studentsList, Comparator.comparing( (Student obj) -> obj.getName() )
					 .thenComparing(obj -> obj.getJobTitle() )
					 .thenComparing(obj -> obj.getAge() )
					 .thenComparing(obj -> obj.getSalary() ) );

System.out.println(studentsList);