HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Sort stream on multiple fields

By Lokesh Gupta | Filed Under: Java 8

Java 8 example to sort stream of objects by multiple fields using comparators and Comparator.thenComparing() method. This method returns a lexicographic-order comparator with another comparator. It gives the same effect as SQL group by clause.

1. Create comparators for multiple fields

To sort on multiple fields, we must first create comparator for each field on which we want to sort the stream. Then chain each comparator in desired order to give group by effect on complete sorting.

//first name comparator
Comparator<Employee> compareByFirstName = Comparator.comparing( Employee::getFirstName );

//last name comparator
Comparator<Employee> compareByLastName = Comparator.comparing( Employee::getLastName );

//Compare by first name and then last name (multiple fields)
Comparator<Employee> compareByFullName = compareByFirstName.thenComparing(compareByLastName);

//Using Comparator - pseudo code
list.stream().sorted( comparator ).collect();

2. Java stream sort on multiple fields – example

Example of using thenComparing() to create Comparator which is capable of sorting by multiple fields.

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

public class Main 
{
	public static void main(String[] args) 
	{
		ArrayList<Employee> employees = getUnsortedEmployeeList();
		
		//Compare by first name and then last name
		Comparator<Employee> compareByName = Comparator
												.comparing(Employee::getFirstName)
												.thenComparing(Employee::getLastName);
		
		List<Employee> sortedEmployees = employees.stream()
										.sorted(compareByName)
										.collect(Collectors.toList());
		
		System.out.println(sortedEmployees);
	}

	private static ArrayList<Employee> getUnsortedEmployeeList() 
	{
		ArrayList<Employee> list = new ArrayList<>();
		list.add( new Employee(2l, "Lokesh", "Gupta") );
		list.add( new Employee(1l, "Alex", "Gussin") );
		list.add( new Employee(4l, "Brian", "Sux") );
		list.add( new Employee(5l, "Neon", "Piper") );
		list.add( new Employee(3l, "David", "Beckham") );
		list.add( new Employee(7l, "Alex", "Beckham") );
		list.add( new Employee(6l, "Brian", "Suxena") );
        return list;
	}
}

Program Output.

[E[id=7, firstName=Alex, 	lastName=Beckham], 
E [id=1, firstName=Alex, 	lastName=Gussin], 
E [id=4, firstName=Brian, 	lastName=Sux], 
E [id=6, firstName=Brian, 	lastName=Suxena], 
E [id=3, firstName=David, 	lastName=Beckham], 
E [id=2, firstName=Lokesh, 	lastName=Gupta], 
E [id=5, firstName=Neon, 	lastName=Piper]]

Drop me your questions in comments section related to sorting on multiple fields in stream of objects in Java 8.

Happy Learning !!

Reference:

Comparator.thenComparing() Java Doc

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Leave a Reply

This comment form is under antispam protection
This comment form is under antispam protection
  Subscribe  
Notify of

Search Tutorials

Java 8 Tutorial

  • Java 8 – Introduction
  • Java 8 – forEach
  • Java 8 – Stream
  • Java 8 – Boxed Stream
  • Java 8 – Lambda Expression
  • Java 8 – Functional Interface
  • Java 8 – Method References
  • Java 8 – Default Method
  • Java 8 – Optionals
  • Java 8 – Predicate
  • Java 8 – Date Time
  • Java 8 – Iterate Directory
  • Java 8 – Read File
  • Java 8 – Write to File
  • Java 8 – WatchService
  • Java 8 – String to Date
  • Java 8 – Join Array
  • Java 8 – Base64
  • Java 8 – Exact Arithmetic
  • Java 8 – Comparator
  • Java 8 – Regex as Predicate
  • Java 8 – Join String
  • Java 8 – Difference Between Dates
  • Internal vs. External Iteration
  • Java 8- SecureRandom

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz