top of page

Coffee and Tips Newsletter

Inscreva-se na nossa newsletter semanal

Nos vemos em breve!

Using Comparator.comparing to sort Java Stream

Writer: JP
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!



















22 Comments


normami.l.e.s.940.4
2 days ago

https://soicaulodechuan.net/ đang thấy mọi người bàn về cách trình bày trang kiểu “dễ nhìn hay không” nên mình mở thử luôn cho biết. Mình chỉ lướt vài phút, chủ yếu xem cảm giác dùng thực tế thế nào chứ không đi sâu nội dung, và thấy họ chia các khối thông tin khá rành mạch nên kéo xuống vẫn không bị mất phương hướng. Thanh menu đặt ngay trên đầu, bấm qua lại mấy mục thì phản hồi nhanh, không phải đợi lâu (kiểu nhẹ tay ấy). Mà màu nền với chữ nhìn vừa mắt, không bị chói nên đọc nhanh cũng đỡ mỏi. Nói chung nếu chỉ cần xem nhanh rồi chuyển phần khác thì ổn, vì các bảng/ô…

Like

ngoongniepgangvoat.1.24.5
Sep 06

https://gamebaidoithuong.fyi/ mình vừa tò mò bấm vào thử vì thấy link được nhắc đâu đó, tưởng sẽ vào xem được chút giao diện. Ai dè vừa mở ra là gặp ngay trang báo lỗi “404 Not Found”, kiểu không tìm thấy tài nguyên trên server nên chẳng có gì để lướt tiếp. Cơ mà trang lỗi nhìn cũng khá sạch sẽ, chữ dễ đọc, không bị nhồi nhét linh tinh nên liếc cái là hiểu ngay chuyện gì đang xảy ra. Kéo xuống dưới còn thấy dòng “Proudly powered by LiteSpeed Web Server” nằm ở cuối trang.

Like

toachdiechngiechl.uan
Sep 05

https://uu88sh.com/ mình thấy dùng na ná vài trang mình hay lướt trước đây, kiểu vào phát là nhận ra ngay luồng chính nằm đâu nên khỏi mất công mò, mình chỉ bật lên xem thử chút thôi mà vẫn kéo qua lại khá trơn tru, mấy khối nội dung xếp gọn nên mắt đỡ phải chạy vòng vòng, cảm giác như họ ưu tiên cho người lười đọc hướng dẫn kiểu mình. Mình thao tác vài cái là quen. Không cần bấm nhiều. Có đoạn PHÁ GẠCH mình thấy ghi hướng dẫn rõ ràng ngay cạnh nội dung. Nhất là dòng nói dùng ← → hoặc A D để di chuyển thanh nhìn cái hiểu liền. Phần PHÁ GẠCH để…

Like

myla.phan236.9
Aug 27

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…

Like

terrygr.a.y.78.4.41
Aug 24

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…

Like
bottom of page