Java Stream sorted example

In this post, we will see how to sort a list with Stream.sorted() method.

Java 8 has introduced Stream.sort() method to sort list of elements conveniently. It helps us to write short and concise functional style code rather than boilerplate code.


java.util.Stream has two overloaded versions of sorted() method.

  1. sorted(): Returns a stream having elements sorted by natural order
  2. sorted(Comparator<? super T> comparator): Returns a stream having elements sorted by provided comparator

💡 Did you know?

If you sort list of Integers using Stream.sorted() method then Comparable interface, implemented by Integer class, will define natural ordering of list of Integers .

Let’s understand how can we use Stream.sorted() to sort list of elements.

Sort List of Integers

We can simply use sorted() method to sort list of integers.

Here, List of Integers is sorted by Comparable interface implemented by Integer class.

As you can see, Integers are compared on this basis of (x &lt; y) ? -1 : ((x == y) ? 0 : 1) logic.

You can pass Comparator.reverseOrder() to sorted method to reverse sort list of Integers.

Comparator.reverseOrder() is static method and provides a comparator that imposes reverse of natural ordering.

Let’s see complete example to sort list of integers.

Output:

[20, 21, 34, 37, 40]
[40, 37, 34, 21, 20]

Sort List of Strings

We can simply use sorted() method to sort list of Strings.

Here, List of Strings is sorted by Comparable interface implemented by String class.

As you can see, Integers are compared on this basis of (x &lt; y) ? -1 : ((x == y) ? 0 : 1) logic.

You can pass Comparator.reverseOrder() to sorted method to reverse sort list of Integers.

Comparator.reverseOrder() is static method and provides a comparator that imposes reverse of natural ordering.

Let’s see complete example to sort list of integers.

Output:

[C++, Java, PHP, Python]
[Python, PHP, Java, C++]

Sort List of custom objects

Sort list of Students by natural order

Create a class named Student.java

Let’s use Stream’s sorted() to sort the list of Students now.

Let’s run above program.

Exception in thread “main” java.lang.ClassCastException: org.arpit.java2blog.Student cannot be cast to java.lang.Comparable
at java.util.Comparators$NaturalOrderComparator.compare(Comparators.java:47)
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
at java.util.TimSort.sort(TimSort.java:220)
at java.util.Arrays.sort(Arrays.java:1512)
at java.util.stream.SortedOps$SizedRefSortingSink.end(SortedOps.java:353)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:483)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:566)
at org.arpit.java2blog.SortListOfStudents.main(SortListOfStudents.java:14)

Did you know why we got exception here?
We got the ClassCastException exception because we did not implement Comparable interface in Student class.

Let’s implement Comparable interface in Student class.

Run SortListOfStudents again, and you will get below output.

[Student [name=Andy, age=17], Student [name=Harshal, age=18], Student [name=Mary, age=20], Student [name=Peter, age=21], Student [name=Peter, age=19]]

As you can see, list of Students is sorted by student name.

Sort list of Students by reverse natural order

Sort list of Students by name in descending order.

Output:

[Student [name=Peter, age=21], Student [name=Peter, age=19], Student [name=Mary, age=20], Student [name=Harshal, age=18], Student [name=Andy, age=17]]

Sort list of Students by age using comparator

Output:

[Student [name=Andy, age=17], Student [name=Harshal, age=18], Student [name=Peter, age=19], Student [name=Mary, age=20], Student [name=Peter, age=21]]

You can also use Comparator.comparing(Function&lt;? super T, ? extends U&gt; keyExtractor) to sort it on the basis of age.
Comparator.comparing() accepts a function that maps a sort key from a type, and returns a Comparator that compares by that sort key.
Let’s say you want to sort list of Students on the basis of age. You can extracts sort key age from Student object and Comparator.comparing() will return a comparator which will sort by that sort key.

Here Comparator.comparing() returns a new Comparator to sort based on age.

We can also use method reference here as we are just calling s.getAge() in the functional interface.

Let’s say you want to sort list of Students on the basis of age in descending order. You can pass another comparator to Comparator.comparing() to make custom sorting based on sort key.

Here,
Comparator.comparing() has two arguments.
Student::getAge to define sort key.
(age1,age2) -&gt; age2 - age1) to define custom sorting on the basis of sort key.

Here is the complete example.

Output:

Sorted list by age ascending: [Student [name=Andy, age=17], Student [name=Harshal, age=18], Student [name=Peter, age=19], Student [name=Mary, age=20], Student [name=Peter, age=21]]
Sorted list by age descending: [Student [name=Peter, age=21], Student [name=Mary, age=20], Student [name=Peter, age=19], Student [name=Harshal, age=18], Student [name=Andy, age=17]]

Sort list of Students by name and age

Let’s say you want to list of students by name and if name is same, then you need to sort by age.

You can use Comparator.thenComparing() with Comparator.comparing() to achieve the same.

Let’s see with the help of example.

Output:

[Student [name=Andy, age=17], Student [name=Harshal, age=18], Student [name=Mary, age=20], Student [name=Peter, age=19], Student [name=Peter, age=21]]

As you can see, there are two students named Peter in the list then, sorted by age.

Excercise

Given a list of Employee objects, you need to sort them of Employee’s name in descending order and return a sorted list of Employee(List<Employee>)
Here is the definition of Employee class.


import_contacts

You may also like:

Related Posts

  • Convert Date to LocalDate in java
    12 January

    Java Date to LocalDate

    In this post, we will see how to convert Date to LocalDate in java. Sometimes, we may need to convert Date to new Java 8 APIs and vice versa. There are multiple ways to convert Date to LocalDate in java. Read also: Convert LocalDate to Date in java Using toInstant() method of Date class You […]

  • Convert LocalDate to Date in java
    11 January

    Java LocalDate to Date

    In this post, we will see how to convert LocalDate to Date. Java 8 has introduced a lot of new APIs for Date and time. There can be many ways to convert Java LocalDateTime to date. Using Instant object You can convert LocalDate to Date using Instant object which we can from Zone. Here is […]

  • 31 December

    Java Stream to List

    In this post, we will see how to convert Stream to List in java. There are multiple ways to convert Stream to List in java. Using Collectors.toList() You can pass Collectors.toList() to Stream.collect() method to convert Stream to List in java. Stream’s collect method performs mutable reduction operation on elements of Stream and Collectors.toList() provides […]

  • 18 November

    Convert LocalDateTime to Timestamp in Java

    In this post, we will how to convert LocalDateTime to Timestamp . Before learning how to convert localdatetime to timestamp, let us learn about LocalDateTime and Timestamp, and understand the importance of this conversion. LocalDateTime LocalDateTime was introcuded in Java 8. LocalDateTime can be imported time package: import java.time.LocalDateTime; LocalDateTime is an immutable object used […]

  • 28 August

    A In-Depth guide to Java 8 Stream API

    In this post, we will see an in-depth overview of Java 8 streams with a lot of examples and exercises. Introduction You may think that Stream must be similar to InputStream or OutputStream, but that’s not the case. A Stream represents a sequence of elements supporting sequential and parallel aggregate operations. Stream does not store […]

  • 26 April

    Java Stream List to Map

    In this post, we will see how to convert List to Map using Stream in java 8. Collectors’s toMap() can be used with Stream to convert List to Map in java. Consider a class Named Movie which have 3 fields – id, name and genre [crayon-600d65ce5e1cc755892538/] Create a list of movies and convert with to […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.