Learnitweb

Sort a stream in Java

1. Introduction

In this tutorial, we’ll discuss ways to sort stream with the help of examples. Stream interface provides following overloaded sorted() methods:

  • Stream sorted()
  • Stream sorted(Comparator comparator)

2. Sort a list of integers

You can use the sorted() method to sort the list in the ascending order.

List<Integer> sortedList = list.stream().sorted().collect(Collectors.toList());

Complete example

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SortStreamExample {

	public static void main(final String[] arguments) {
		// create list
		List<Integer> list = Arrays.asList(9, 5, 7, 2, 8, 4, 3, 6, 1);

		// sort the list
		List<Integer> sortedList = list.stream().sorted().collect(Collectors.toList());

		// print the list
		sortedList.forEach(System.out::println);
	}
}

Output

1
2
3
4
5
6
7
8
9

3. Sort a list of integers in descending order

You can pass the Comparator.reverseOrder() to the sorted() method of Stream.

List<Integer> sortedList = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class SortStreamExample {

	public static void main(final String[] arguments) {
		// create list
		List<Integer> list = Arrays.asList(9, 5, 7, 2, 8, 4, 3, 6, 1);

		List<Integer> sortedList = list.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());

		// print the list
		sortedList.forEach(System.out::println);
	}
}

Output

9
8
7
6
5
4
3
2
1

4. Sort list of objects

Consider a list of Employee objects. Employee object has name and salary as fields. We’ll sort the list of Employee objects by comparing salary field in ascending and descending order.

Following is the Employee object:

public class Employee {
	String name;
	int salary;

	public Employee(String name, int salary) {
		super();
		this.name = name;
		this.salary = salary;
	}
// getter, setter, toString() removed from brevity
}

The sorted() method accepts a Comparator as an argument. You can pass lambda expression to the sorted() method.

List<Employee> sortedList = list.stream().sorted((emp1, emp2) -> emp1.getSalary() - emp2.getSalary())
				.collect(Collectors.toList());

You can also use Comparator.comparingInt() method in our case to compare salaries as salary is an integer.

List<Employee> sortedList = list.stream().sorted(Comparator.comparingInt(Employee::getSalary))
				.collect(Collectors.toList());

Complete example

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortStreamExample {

	public static void main(final String[] arguments) {
		// create list
		List<Employee> list = new ArrayList();
		Employee employee1 = new Employee("Mat", 1000);
		Employee employee2 = new Employee("James", 1700);
		Employee employee3 = new Employee("Anna", 2300);
		Employee employee4 = new Employee("Kevin", 1900);
		Employee employee5 = new Employee("Julie", 1500);

		list.add(employee1);
		list.add(employee2);
		list.add(employee3);
		list.add(employee4);
		list.add(employee5);

		// using lambda 
		List<Employee> sortedList1 = list.stream().sorted((emp1, emp2) -> emp1.getSalary() - emp2.getSalary())
				.collect(Collectors.toList());

		// Comparator.comparingInt()
		List<Employee> sortedList2 = list.stream().sorted(Comparator.comparingInt(Employee::getSalary))
				.collect(Collectors.toList());

		// print the list
		sortedList1.forEach(System.out::println);
		sortedList2.forEach(System.out::println);
	}
}

Output

Employee [name=Mat, salary=1000]
Employee [name=Julie, salary=1500]
Employee [name=James, salary=1700]
Employee [name=Kevin, salary=1900]
Employee [name=Anna, salary=2300]
Employee [name=Mat, salary=1000]
Employee [name=Julie, salary=1500]
Employee [name=James, salary=1700]
Employee [name=Kevin, salary=1900]
Employee [name=Anna, salary=2300]

4.1 Sort list of objects in reverse order

You can use the reversed() method to get the result in reverse order.

List<Employee> sortedList = list.stream().sorted(Comparator.comparingInt(Employee::getSalary).reversed())
		.collect(Collectors.toList());

4.2 Sort by name

List<Employee> sortedList = list.stream().sorted(Comparator.comparing(Employee::getName))
		.collect(Collectors.toList());

5. Custom sort

We can create a custom Comparator and pass to the sorted() method. We’ll create a custom Comparator just for demonstration.

import java.util.Comparator;

public class FirstNameSorter implements Comparator<Employee> {

	@Override
	public int compare(Employee emp1, Employee emp2) {
		return emp2.getName().compareToIgnoreCase(emp1.getName());
	}
}

You can pass the Comparator to the sorted() method.

// using lambda
List<Employee> sortedList = list.stream().sorted(new FirstNameSorter()).collect(Collectors.toList());
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class SortStreamExample {

	public static void main(final String[] arguments) {
		// create list
		List<Employee> list = new ArrayList();
		Employee employee1 = new Employee("Mat", 1000);
		Employee employee2 = new Employee("James", 1700);
		Employee employee3 = new Employee("Anna", 2300);
		Employee employee4 = new Employee("Kevin", 1900);
		Employee employee5 = new Employee("Julie", 1500);

		list.add(employee1);
		list.add(employee2);
		list.add(employee3);
		list.add(employee4);
		list.add(employee5);

		// using lambda
		List<Employee> sortedList = list.stream().sorted(new FirstNameSorter()).collect(Collectors.toList());

		// print the list
		sortedList.forEach(System.out::println);

	}
}

Output

Employee [name=Mat, salary=1000]
Employee [name=Kevin, salary=1900]
Employee [name=Julie, salary=1500]
Employee [name=James, salary=1700]
Employee [name=Anna, salary=2300]