Using Comparator.comparing to sort Java Stream
- JP

- Jun 25, 2023
- 2 min read
Updated: Feb 5, 2024

Introduction
Sorting data is a common task in many software development projects. When working with collections of objects in Java, a powerful and flexible approach to sorting is to use the Comparator.comparing interface in conjunction with Streams. In this post, we are going to show that using Comparator.comparing to sort Java Stream can make sorting elegant and efficient.
What is the Comparator.comparing interface?
The Comparator.comparing interface is a feature introduced in Java 8 as part of the java.util.Comparator. package. It provides a static method called comparing that allows you to specify a key function (sort key) to compare objects. This function is used to extract a value from an object and compare it against that value during sorting.
Flexibility in sorting with Comparator.comparing
One of the main advantages of the Comparator.comparing interface is its flexibility. With it, we can perform sorting in different fields of an object, allowing the creation of complex sorting logic in a simple and concise way. Notice in the code below that simply in the sorted() method, we pass the Comparator.comparing interface as an argument, which in turn, passes the city field as an argument using method reference (People::getCity) performing the sort by this field.
Output
Monica
John
Mary
Anthony
Seth
Multi-criteria ordering
Often, it is necessary to perform sorting based on multiple criteria. This is easily achieved with the Comparator.comparing. interface by simply chaining together several comparing methods, each specifying a different criterion. Java will carry out the ordering according to the specified sequence. For example, we can sort the same list by city and then by name: Comparator.comparing(People::getCity).thenComparing(People:: getName).
Ascending and descending sort
Another important advantage of the Comparator.comparing interface is the ability to perform sorting in both ascending and descending order. To do this, just chain the method reversed() as in the code below:
Output
Seth
Mary
John
Anthony
Monica
Efficiency and simplicity
By using the Comparator.comparing interface in conjunction with Streams, sorting becomes more efficient and elegant. The combination of these features allows you to write clean code that is easy to read and maintain. Furthermore, Java internally optimizes sorting using efficient algorithms, resulting in satisfactory performance even for large datasets.
Final conclusion
The Comparator.comparing interface is a powerful tool to perform the sorting of Streams in Java. Its flexibility, ascending and descending sorting capabilities, support for multiple criteria, and efficient execution make it a valuable choice for any Java developer. By taking advantage of this interface, we can obtain a more concise, less verbose and efficient code, facilitating the manipulation of objects in a Stream.
Hope you enjoyed!



789 Club bữa mình thấy nhắc đâu đó nên bấm vào nghía thử cho biết, kiểu xem giao diện có dễ dùng không thôi. Vừa vào là thấy trang làm khá gọn, nền nã, nhìn không bị “nhồi” chữ nên đỡ mệt mắt. Mình để ý họ đặt mấy tiêu đề lớn kiểu nói về cam kết đổi mới và bền vững, đọc lướt cũng hiểu họ muốn đi theo hướng dài hạn chứ không phải kiểu làm cho có. Mình không ngồi đọc hết nội dung, chỉ kéo xuống xem cách chia khối, thấy các phần được tách rõ ràng nên người mới vào cũng không bị lạc. Nói chung cảm giác như họ ưu tiên trải nghiệm xem…
https://ivibetbonusbr.com/bonus-tipos-e-promocoes/ eu caí aí meio sem intenção, só pra entender como eles explicam essas paradas sem ficar pulando de página em página. O que achei legal é que o texto é bem direto e dá pra sacar rápido a diferença entre as promoções, tipo quando eles comentam que cashback costuma ter rollover menor (e às vezes nem tem extra, dependendo da campanha). Isso já evita aquela dúvida chata de “tá, mas qual vale mais a pena ler primeiro?”. Também curti que não fica jogando termos soltos, eles dão um contexto simples e pronto, sem enrolação. E visualmente ajuda bastante porque fica tudo separado em blocos com títulos bem claros, então dá pra bater o olho e achar o trecho que…
https://www.kjcattle.com/ mình ghé thử do thấy mọi người bàn về “liên minh” này, nên vào xem giao diện ra sao. Trang mở lên là thấy họ viết phần giới thiệu khá dễ hiểu, kiểu nói đây là nền tảng tổng hợp nhiều thương hiệu và có nhắc chuyện dùng chung một tài khoản cho nhiều nền tảng nên đọc lướt cũng nắm được ý. Mình thích nhất là cách họ trình bày không rối: chữ vừa phải, đoạn nào ra đoạn nấy, nhìn một vòng là biết chỗ nào đang nói gì. Mấy khối thông tin được chia theo tiêu đề rõ ràng nên không phải kéo lên kéo xuống để tìm, và phần heading/box nội dung trên trang sắp…
Hitclub 957 mình thấy bạn bè nhắc nên tiện tay bấm vào xem thử, kiểu xem giao diện thôi chứ không định đọc sâu. Vào cái là thấy họ làm bố cục khá thoáng, nhìn nhẹ mắt chứ không bị nhồi chữ. Mình để ý mấy tiêu đề kiểu “Cam kết đổi mới và bền vững” đọc lướt là hiểu hướng họ muốn nói, nghe cũng hợp với mảng kiến trúc. Phần giới thiệu về việc kết hợp sáng tạo với chức năng viết vừa đủ, không cố làm màu nên cảm giác dễ tin hơn. Kéo xuống mấy khối nội dung được chia gọn gàng, khoảng trắng ổn nên lướt nhanh vẫn nắm được ý. Nói chung mình thích…
https://kjcvip.net/ mình thấy bạn bè nhắc hoài nên ghé thử cho biết, chủ yếu xem trang họ làm ra sao chứ chưa có thời gian ngồi tìm hiểu sâu. Cảm giác đầu tiên là giao diện nhìn khá hiện đại, bố cục chia thành từng mảng rõ nên lướt một vòng cũng không bị ngợp. Mình để ý phần tin tức cập nhật theo ngày đặt khá dễ thấy, kiểu ai thích xem nhanh thông tin mới thì tiện. Mấy tiêu đề và khối nội dung canh thẳng hàng, chữ nghĩa rõ ràng nên mắt đỡ phải “căng” để tìm. Nói chung vào xem thử cho vui mà thấy cách họ chia block và đặt mục tin tức ngay trên…