Before using Stream API lets do it using normal java way.
Suppose you have below Employee class:
class Employee{ int age; String name; public Employee(int age, String name) { this.age=age; this.name=name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return String.valueOf(age) + "-" +name; } }
Have a helper which implements Comparator interface like below:
class EmployeeAgeComparator implements Comparator{ public int compare(Object o1, Object o2) { Employee e1=(Employee)o1; Employee e2=(Employee)o2; return e1.age - e2.age; } }
In client class:
public class Manager{ public static void main(String[] args) { List<Employee> list=new ArrayList(); list.add(new Employee(41,"Pressy")); list.add(new Employee(10,"Paddy")); list.add(new Employee(35,"Ashy")); System.out.println("Before sort:"+ list); Collections.sort(list, new EmployeeAgeComparator()); //To sort by Age. System.out.println("After sort:" + list); } }
Now lets see how we can do the same using Java 8 Streams API.
Now you don’t need the helper class like above. So, the client class would look like below:
public class Manager { public static void main(String[] args) { Employee e1=new Employee(41,"Pressy"); Employee e2=new Employee(10,"Paddy"); Employee e3=new Employee(35,"Ashy"); Employee e4=new Employee(41,"Saro"); List<Employee> list=new ArrayList(); list.add(e1); list.add(e2); list.add(e3); list.add(e4); System.out.println("Before sort:"+ list); System.out.println("After sort:"); Comparator<Employee> comparator1=(x,y) -> x.getAge() - y.getAge(); list.stream().sorted(comparator1).forEach(System.out::println); } }
Sorting a Stream by Multiple Fields in Java:
public class Manager { public static void main(String[] args) { Employee e1=new Employee(41,"Pressy"); Employee e2=new Employee(10,"Paddy"); Employee e3=new Employee(35,"Ashy"); Employee e4=new Employee(41,"Saro"); List<Employee> list=new ArrayList(); list.add(e1); list.add(e2); list.add(e3); list.add(e4); System.out.println("Before sort:"+ list); System.out.println("After sort:"); Comparator<Employee> comparator1=(x,y) -> x.getAge() - y.getAge(); Comparator<Employee> comparator2=(x,y) -> x.getName().compareTo(y.getName()); list.stream().sorted( comparator1 .thenComparing(comparator2) ).forEach(System.out::println); } }