Java

What is Stream.sorted() Method in Java

In Java, there can be certain instances where the programmer needs to sort the entries in accordance with the requirement. For instance, retrieving the unsorted or randomly generated values in a specific (ascending or descending) manner. In such situations, the “Stream.sorted()” method helps sort the data effectively at the developer’s end.

This article will elaborate on using and implementing the “Stream.sorted()” method in Java.

What is the “Stream.sorted()” Method in Java?

The “Stream.sorted()” method corresponds to the “Stream” interface. This method gives a sorted stream without affecting the elements/items ordering in the original stream.

Syntax

Case 1: No Parameter

stream.sorted()

 

Case 2: With Parameter

stream.sorted(comp)

 

In this syntax, “comp” refers to the comparator based on which the sorting will be done.

Before proceeding to the examples, make sure to include the following package. This package comprises classes, interfaces, etc, to allow functional-style operations on the elements:

import java.util.stream.*;

 

Example 1: Applying the “Stream.sorted()” Method to Sort (Ascending and Descending) the Integers in Java

The “Stream.of()” method is used to create a sequential stream for the given elements. In this example, this method can be applied combined with the “Stream.sorted()” method to sort the integers stream in ascending and descending manner:

public class sorted {
 public static void main(String[] args) {
  Stream<Integer> sortStream1 = Stream.of(2, 4, 3, 5, 1);
  Stream<Integer> sortStream2 = Stream.of(9, 6, 7, 8, 10);
  System.out.println("The first stream is: ");
  sortStream1.sorted().forEach(System.out::println);
  System.out.println("\nThe second stream is: ");
  sortStream2.sorted((a, b)->b-a).forEach(System.out::println);
}}

 

In this code snippet:

  • Create two different integer streams via the “of()” method.
  • After that, associate the “sorted()” method with the created former stream to sort the stream in “ascending” order.
  • Now, apply the “sorted()” method again with the latter stream to return the stream in “descending” order in accordance with the specified comparator, i.e., “b-a”.
  • Lastly, display the sorted integers stream in both cases on the console.

Output

In this output, it can be observed that both streams are sorted accordingly.

Before heading to the next example, include the below-provided example to access all the classes and methods:

import java.util.*;

 

Example 2: Applying the “Stream.sorted()” Method to Sort the Class Objects

In this particular example, the discussed method can be implemented upon the class objects to sort the passed values:

class Data {
 int id;
 String name;
 Data(int id,String name) {
  this.id = id;
  this.name = name;
}
 public String toString() {
  return "id=" + this.id
  + ", name=" + this.name;
}}
class streamsorted {
 public static void main(String[] args) {
  List<Data> list = new ArrayList<Data>();
  list.add(new Data(2,"Harry"));
  list.add(new Data(1,"David"));
  list.add(new Data(3,"Tom"));
  Stream<Data> stream = list.stream();
  stream.sorted((e1, e2) -> e1.id - e2.id).forEach(System.out::println);
}}

 

In these lines of code, perform the following steps:

  • Firstly, declare a class named “Data”.
  • In its definition, specify the stated variables.
  • In the next step, include a parameterized class constructor having the parameters identical to the specified variables.
  • In the constructor definition, refer to the specified variables, and allocate them the passed argument values via “this”.
  • Now, override the “toString()” method to return the passed values.
  • In the “main()” method, create a list of the class objects and add the stated passed values to the list via the associated “add()” method.
  • After that, fetch the stream from the list via the “stream()” method.
  • Also, apply the “sorted()” method with the stated comparator that compares two objects based on “id” in an “ascending” manner.
  • Finally, apply the “forEach()” method to log the sorted objects stream on the console.

Output

In this outcome, it can be analyzed that the object values are sorted appropriately.

Conclusion

The “Stream.sorted()” is the method corresponding to the “Stream” interface that gives a sorted stream without affecting the items/elements ordering in the original stream. This method sorts the elements in a default way as well as based on the specified comparator. This blog discussed using and implementing the “Stream.sorted()” method in Java.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.