Which method is used to sort elements in a stream?

Which method is used to sort elements in a stream?

a) sort()
b) order()
c) sorted()
d) arrange()

Answer:

c) sorted()

Explanation:

The sorted() method in the Stream API is used to sort the elements in a stream either in natural order or using a custom comparator. This method is an intermediate operation, meaning it creates a new stream with the sorted elements but does not trigger the execution of the stream pipeline. The sorted() method is particularly useful when you need to arrange the elements of a stream in a specific order, such as sorting a list of names alphabetically or a list of numbers in ascending order.

When used without arguments, the sorted() method sorts the elements in their natural order, which is determined by the Comparable implementation of the elements. For example, strings are sorted lexicographically, and numbers are sorted in ascending order. If you need to sort elements in a different order, you can provide a custom Comparator to the sorted() method. This allows you to define your own sorting criteria, such as sorting objects based on a specific attribute or sorting numbers in descending order.

The sorted() method is often used in combination with other stream operations, such as map() or filter(), to process and sort data in a functional style. Since it is an intermediate operation, the actual sorting does not take place until a terminal operation, such as collect() or forEach(), is invoked. The sorted() method is a versatile tool for organizing and processing data in Java streams.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top