Saturday, 8 August 2020

Sort a list using Streams

 In this post, I am going to explain how to sort a list of items using Strems#sort method.

'java.util.stream.Stream' interface provides the following methods to sort a stream.

 

Stream<T> sorted()

Returns a stream consisting of the elements of this stream, sorted according to the natural order.

 

Stream<T> sorted(Comparator<? super T> comparator)

Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.

 

For example,

a. Below snippet converts list of integers in ascending order.

List<Integer> ascendingOrderItems = items.stream().sorted().collect(Collectors.toList());

                 

b. Below snippet converts list of integers in descending order.

List<Integer> descendingOrderItems = items.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

 

Find the below working application.

 

App.java

package com.sample.app;

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

public class App {

	public static void main(String args[]) {
		List<Integer> items = new ArrayList<>(Arrays.asList(1, 34, 2, 45, 6, 3, 10, 45));
		
		List<Integer> ascendingOrderItems = items.stream().sorted().collect(Collectors.toList());
		List<Integer> descendingOrderItems = items.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
		
		System.out.println(items);
		System.out.println(ascendingOrderItems);
		System.out.println(descendingOrderItems);
	}
}

Output

[1, 34, 2, 45, 6, 3, 10, 45]

[1, 2, 3, 6, 10, 34, 45, 45]

[45, 45, 34, 10, 6, 3, 2, 1]

 

How to sort custom objects?

To use the sort() method, custom class must implement Comparable interface.

 

Employee.java

package com.sample.app.model;

public class Employee implements Comparable<Employee> {

	private Integer id;
	private String firstName;
	private String lastName;

	public Employee(Integer id, String firstName, String lastName) {
		super();
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
	}

	@Override
	public int compareTo(Employee emp) {
		return this.id.compareTo(emp.getId());
	}

}

As you see the definition of Employee class, I implemented the comparison (compareTo method) using employee id.

 

Following snippet sort the employees in the ascending order of their ids.

List<Employee> ascendingOrderById = emps.stream().sorted().collect(Collectors.toList());

 

Following snippet sort the employees in the ascending order of their ids.

List<Employee> desscendingOrderById = emps.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

 

App.java

package com.sample.app;

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

import com.sample.app.model.Employee;

public class App {

	public static void main(String args[]) {
		Employee emp1 = new Employee(123, "Ram", "Gurram");
		Employee emp2 = new Employee(1, "Gopi", "Battu");
		Employee emp3 = new Employee(23, "Bala", "Murugan");
		Employee emp4 = new Employee(15, "Abhishek", "Gupta");
		Employee emp5 = new Employee(11, "Anand", "Bandaru");
		
		List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);
		
		List<Employee> ascendingOrderById = emps.stream().sorted().collect(Collectors.toList());
		List<Employee> desscendingOrderById = emps.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
		
		System.out.println(emps + "\n");
		System.out.println(ascendingOrderById + "\n");
		System.out.println(desscendingOrderById);
	}
}

Output

[Employee [id=123, firstName=Ram, lastName=Gurram], Employee [id=1, firstName=Gopi, lastName=Battu], Employee [id=23, firstName=Bala, lastName=Murugan], Employee [id=15, firstName=Abhishek, lastName=Gupta], Employee [id=11, firstName=Anand, lastName=Bandaru]]

[Employee [id=1, firstName=Gopi, lastName=Battu], Employee [id=11, firstName=Anand, lastName=Bandaru], Employee [id=15, firstName=Abhishek, lastName=Gupta], Employee [id=23, firstName=Bala, lastName=Murugan], Employee [id=123, firstName=Ram, lastName=Gurram]]

[Employee [id=123, firstName=Ram, lastName=Gurram], Employee [id=23, firstName=Bala, lastName=Murugan], Employee [id=15, firstName=Abhishek, lastName=Gupta], Employee [id=11, firstName=Anand, lastName=Bandaru], Employee [id=1, firstName=Gopi, lastName=Battu]]

We can even provide custom comparators.

 

Below snippet sort the employees by their firstName.

List<Employee> ascendingOrderByFirstName = emps.stream()

                                    .sorted((e1, e2) -> e1.getFirstName()

                                    .compareTo(e2.getFirstName()))

                                    .collect(Collectors.toList());

                 

Below snippet sort the employees by their lastName.

List<Employee> ascendingOrderByLastName = emps.stream()

                                    .sorted((e1, e2) -> e1.getLastName()

                                    .compareTo(e2.getLastName()))

                                    .collect(Collectors.toList());

 

Find the below working application.

 

App.java

package com.sample.app;

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

import com.sample.app.model.Employee;

public class App {

	public static void main(String args[]) {
		Employee emp1 = new Employee(123, "Ram", "Gurram");
		Employee emp2 = new Employee(1, "Gopi", "Battu");
		Employee emp3 = new Employee(23, "Bala", "Murugan");
		Employee emp4 = new Employee(15, "Abhishek", "Gupta");
		Employee emp5 = new Employee(11, "Anand", "Bandaru");

		List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);

		List<Employee> ascendingOrderByFirstName = emps.stream()
				.sorted((e1, e2) -> e1.getFirstName()
				.compareTo(e2.getFirstName()))
				.collect(Collectors.toList());
		
		List<Employee> ascendingOrderByLastName = emps.stream()
				.sorted((e1, e2) -> e1.getLastName()
				.compareTo(e2.getLastName()))
				.collect(Collectors.toList());

		System.out.println(emps + "\n");
		System.out.println(ascendingOrderByFirstName + "\n");
		System.out.println(ascendingOrderByLastName);
	}
}

Output

[Employee [id=123, firstName=Ram, lastName=Gurram], Employee [id=1, firstName=Gopi, lastName=Battu], Employee [id=23, firstName=Bala, lastName=Murugan], Employee [id=15, firstName=Abhishek, lastName=Gupta], Employee [id=11, firstName=Anand, lastName=Bandaru]]

[Employee [id=15, firstName=Abhishek, lastName=Gupta], Employee [id=11, firstName=Anand, lastName=Bandaru], Employee [id=23, firstName=Bala, lastName=Murugan], Employee [id=1, firstName=Gopi, lastName=Battu], Employee [id=123, firstName=Ram, lastName=Gurram]]

[Employee [id=11, firstName=Anand, lastName=Bandaru], Employee [id=1, firstName=Gopi, lastName=Battu], Employee [id=15, firstName=Abhishek, lastName=Gupta], Employee [id=123, firstName=Ram, lastName=Gurram], Employee [id=23, firstName=Bala, lastName=Murugan]]



Previous                                                    Next                                                    Home

No comments:

Post a Comment