Skip to main content

Posts

Showing posts from 2025

Sort data with Streams in Java

Sorting refers to the mechanism of arranging/re-arranging something in a specific order. When it comes to java, we talk about placing the elements of an array or a list (Collection) in either Ascending or Descending order. There are multiple ways of achieving the desired order of elements in a collection, but here we will see how to make efficient use of Stream API which was introduced since JDK 8. As we already know, streams work with Lambda expressions and Functional Interfaces and provide some out of the box features which make developers' life easier. To sort a collection, streams have the inbuilt method sorted()    which has the following 2 method signatures: 1. Stream < T > sorted (); If we have to use this method, the elements of collection must be comparable i.e. the element object must implement Comparable interface. It will sort the collection according to the natural order of underlying object. 2. Stream < T > sorted ( Comparator <? super T > compa...