How to sort an array list with stream.sorted() in Java 8
By:smashplus
                        
                    How to sort an array list with stream.sorted() in Java 8
Quick Answer:
In this post, we will discuss how to sort a ArrayList with steam API. We consider normal List<String> and List of the custom object in the example.
A. If you have a simple list, we can sort by invoking the steam.sorted() in the following way
A.1. The simple way to do the sorting is by following the natural order
List<String> sortedList = list.stream().sorted().collect(Collectors.toList()); 
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class ListManager {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.add("India");
myList.add("Brazil");
myList.add("Argentina");
List<String> sortedList = myList.stream().sorted().collect(Collectors.toList());
sortedList.forEach(System.out::println);
}
}
output:
Argentina
Brazil
India
A.2. If you want to do the sorting in reverse order for a simple list,
List<String> sortedList = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()); 
B. If the requirement to sort a list with a custom object
If you have an Employee list that needs to sort based on the employee's salary, see the code below.
package com.sp.stream;import java.util.Arrays;import java.util.Comparator;import java.util.List;import java.util.stream.Collectors;public class StreamSortObjectApplication {static List<Employee> employees = Arrays.asList(new Employee("Jon", 3000),new Employee("Van H", 1000),new Employee("Hein L", 1050),new Employee("Von Mu", 4223),new Employee("Joe Felix", 3450));public static void main(String[] args) {List<Employee> sortedList = employees.stream().sorted(Comparator.comparingInt(Employee::getSalary)).collect(Collectors.toList());sortedList.forEach(System.out::println);}static class Employee {private String name;private int salary;public Employee(String name, int salary) {this.name = name;this.salary = salary;}public String getName() {return name;}public int getSalary() {return salary;}@Overridepublic String toString() {return "Employee{" +"name='" + name + '\'' +", salary=" + salary +'}';}}}OutputEmployee{name='Van H', salary=1000}Employee{name='Hein L', salary=1050}Employee{name='Jon', salary=3000}Employee{name='Joe Felix', salary=3450}Employee{name='Von Mu', salary=4223}
We can sort by name using the getName method instead of using getSalary
List<Employee> sortedList = employees.stream()
.sorted(Comparator.comparingInt(Employee::getName))
.collect(Collectors.toList());