Sorting is a common technique in any programming language and has several advantages. Sorting helps to reduce time complexities and has different use cases, such as searching algorithms, divide and conquer methods, database algorithms, data structure algorithms, and others.
Sorting is arranging the data in a particular structure, either ascending or descending, based on the relationship of the data items. Java provides sorting techniques like Stream.sorted(), which returns a stream of elements from the original stream, according to the natural order. Let us understand how to sort a list with Stream.sorted() in Java.
What are streams in Java?
Java streams represent a sequence of items and take input from the Collections, Arrays, or I/O channels. Programmers especially use streams to compute items based on the pipelined methods without modifying the original value of the object.
The most critical noting point is streams are not a data structure that stores data values. Streams are a pipeline through which data will flow, allowing specified functions to work on the data, i.e., functional.
Syntax:
Stream<T> sorted()
Here, the Stream indicates an interface, and T
specifies the type of stream elements.
Sorting List of Integers using Stream.sorted()
The sorted() method of the Stream interface returns a stream consisting of the items of the original stream, sorted based on the order given. If the method does not find Comparable elements of the stream, the Java compiler will throw a "java.lang.ClassCastException" upon execution.
Code Snippet:
import java.util.*;
public class demo {
public static void main(String[] args)
{
List<Integer> l = Arrays.asList(-3, -10, 1, -43, 6, 38, 0, 96);
System.out.println("We sorted the elements of the Java list : ");
l.stream().sorted().forEach(System.out::println);
}
}
Output:
Explanation:
In this example, we created a list "l" through the asList() method with eight integer values (both positive and negative). Then, we used the stream() for streaming them together and run the sorted() method. These will print the integers in the natural order, i.e., ascending order.
Code Snippet:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class demo {
public static void main(String[] args)
{
List<Integer> l = Arrays.asList(-3, -34, 5, -7, 8, 67, 0, 21);
List<Integer> res = l.stream().sorted().collect(Collectors.toList());
System.out.println(l);
System.out.println(res);
}
}
Output:
Explanation:
If you want to save the original list of integers, use the collect() method to keep the original array unmodified.
But we also saved the results of the sorted elements of the new list, helping users to use both if they need them afterwards.
In descending order:
By default, the Stream.sorted() method sorts the list elements into natural order, i.e., ascending order. So, users can also sort the list in descending order too. Use the Collections.sort() and Collections.reverseOrder() method to apply the sorting order.
Code Snippet:
import java.util.*;
public class demo {
public static void main(String[] args)
{
List<Integer> l = new ArrayList<Integer>();
l.add(20);
l.add(76);
l.add(23);
l.add(19);
l.add(44);
Collections.sort(l, Collections.reverseOrder());
System.out.println(
"We have sorted the list elements in descending order using the Collection.reverseOrder() and Collections.sort() :\n" + l);
}
}
Output:
Sorting List of Strings using Stream.sorted()
However, if users want to sort a list of strings, they can also use the same technique on string values and sort in the natural order.
Code Snippet:
import java.util.*;
public class demo {
public static void main(String[] args)
{
List<String> students = Arrays.asList("Abhishekh", "Justin", "Kareena", "Siddharth", "Sam", "Rishi", "Prithvi", "Xavier");
System.out.println("The sorted list of students is : ");
students.stream().sorted().forEach(System.out::println);
}
}
Output:
Explanation:
We only made a list with the following names of students, and the Stream.sorted() method sorted the names in the natural, i.e., ascending order.
Code Snippet:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class demo {
public static void main(String[] args)
{
List<String> l = Arrays.asList("Abhishekh", "Siddharth", "Kareena", "Sam", "Justin", "Rishi", "Prithvi", "Xavier");
List<String> res = l.stream().sorted().collect(Collectors.toList());
System.out.println(l);
System.out.println(res);
}
}
Output:
Explanation:
We have sorted the string list again keeping the original list unchanged like did in sorting a list of integers.
In descending order:
Code Snippet:
import java.util.*;
public class demo {
public static void main(String[] args)
{
List<String> l = new ArrayList<String>();
l.add("Siddharth");
l.add("Pallavi");
l.add("Ashish");
l.add("Sam");
l.add("Mishmi");
Collections.sort(l, Collections.reverseOrder());
System.out.println(
"We have sorted the list elements in descending order using the Collection.reverseOrder() and Collections.sort() :\n" + l);
}
}
Output:
Sorting Using Comparator:
While Comparators created by methods such as comparing() and comparing () are too easy to use and fast. The comparator technique only needs a sorting key.
Code Snippet:
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args)
{
demo a = new demo("Siddharth", 30);
demo b = new demo("Ajay", 10);
demo c = new demo("Survi", 35);
demo d = new demo("Paritush", 28);
List<demo> l
= Arrays.asList(b, a, d, c);
System.out.println("Before we sorted the list:");
l.forEach(demo
-> System.out.println("Employee age "
+ demo.emp_age()));
Collections.sort(l,
Comparator.comparingInt(
demo::emp_age));
System.out.println("\nAfter we sorted the list:");
l.forEach(demo
-> System.out.println("Employee age "
+ demo.emp_age()));
}
}
class demo implements Comparable<demo> {
public String emp_name;
public int emp_age;
public demo(String emp_name, int emp_age)
{
this.emp_name = emp_name;
this.emp_age = emp_age;
}
public int compareTo(demo a)
{
return emp_name.compareTo(a.emp_name);
}
public String getName()
{
return emp_name;
}
public void setName(String emp_name)
{
this.emp_name = emp_name;
}
public int emp_age()
{
return emp_age;
}
public void setAge(int emp_age)
{
this.emp_age = emp_age;
}
@Override
public String toString()
{
return "demo [name=" + emp_name
+ ", age=" + emp_age + "]";
}
}
Output:
Sorting using Custom Objects with Stream.sorted(Comparator<? super T> comparator)
Code Snippet:
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class demo {
static List<Empl> students = Arrays.asList(
new Empl("Siddharth", 30),
new Empl("Paritush", 28),
new Empl("Survi", 35),
new Empl("Ajay", 32),
new Empl("Eliza", 24));
public static void main(String[] args) {
List<Empl> res = students.stream()
.sorted(Comparator.comparingInt(Empl::getAge))
.collect(Collectors.toList());
res.forEach(System.out::println);
}
static class Empl {
private String emp_name;
private int emp_age;
public Empl(String emp_name, int emp_age) {
this.emp_name = emp_name;
this.emp_age = emp_age;
}
public String getName() {
return emp_name;
}
public void setName(String emp_name) {
this.emp_name = emp_name;
}
public int getAge() {
return emp_age;
}
public void setAge(int emp_age) {
this.emp_age = emp_age;
}
@Override
public String toString() {
return "Employee{" +
"name='" + emp_name + '\'' +
", age=" + emp_age +
'}';
}
}
}
Output:
Explanation:
In the above example, we have created a list of Employee details. We have streamed the list and used the sorted() method with the Comparator. Then, we used the comparingInt() method and applied the employees' age through the Empl::getAge method reference.
These return a comparator and list the names of the employees in the naturally sorted order according to the Employees' age.
Conclusion
This article gives a detailed understanding of sorting list elements using the Java Stream.sorted() method. We have covered everything regarding the Stream interface with the sorted() method, sorted Comparable integers and strings, sorted in ascending and descending order, and used a comparator with built-in Comparator for custom objects to sort the list items.