How to sort list in Java 8
In Java 8, the elements of a list are sorted by calling stream.sorted()
method of Stream
interface. As we know, Streams bring functional programming to Java and are supported starting in Java 8.
Sorting is an intermediate operation of the stream pipeline. We can chain multiple intermediate operations such as filter, map, etc.
Similar Post: How to find distinct elements in a list in Java
sorted()
is an overloaded method of Stream
interface:
1. sorted()
– sort the list according to the natural sorting order and returns a stream consisting of the elements of this stream.
2. sorted(Comparator<? super T> comparator)
– sort the list according to the provided and returns a stream consisting of the elements of this stream.
Let’s jump to the actual part of sorting a list:
#1 Sorting the elements of a list in the default natural sorting order.
package org.websparrow.sorting;
import java.util.Arrays;
import java.util.List;
public class Java8Sorting {
public static void main(String[] args) {
List<String> students = Arrays.asList(
"Sandeep", "Abhinav", "Gaurav",
"Prince", "Rohit", "Deepika");
System.out.println("==== BEFORE SORTING =====");
students.stream().forEach(System.out::println);
System.out.println("==== AFTER SORTING =====");
students.stream().sorted().forEach(System.out::println);
}
}
Output
==== BEFORE SORTING =====
Sandeep
Abhinav
Gaurav
Prince
Rohit
Deepika
==== AFTER SORTING =====
Abhinav
Deepika
Gaurav
Prince
Rohit
Sandeep
Passing Comparator.naturalOrder()
as argument in sorted(Comparator.naturalOrder())
method bring the same output as shown above.
students.stream()
.sorted(Comparator.naturalOrder())
.forEach(System.out::println);
// Old days technique
students.stream()
.sorted((o1, o2) -> o1.compareTo(o2))
.forEach(System.out::println);
#2 Sorting a list in reverse order. Comparator.reverseOrder()
return the reverse of the natural ordering.
package org.websparrow.sorting;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Java8Sorting2 {
public static void main(String[] args) {
List<String> students = Arrays.asList("Sandeep", "Abhinav", "Gaurav",
"Prince", "Rohit", "Deepika");
System.out.println("==== BEFORE SORTING =====");
students.stream().forEach(System.out::println);
System.out.println("==== AFTER SORTING (REVERED ORDER) =====");
students.stream().sorted(Comparator.reverseOrder())
.forEach(System.out::println);
}
}
Output
==== BEFORE SORTING =====
Sandeep
Abhinav
Gaurav
Prince
Rohit
Deepika
==== AFTER SORTING (REVERED ORDER) =====
Sandeep
Rohit
Prince
Gaurav
Deepika
Abhinav
(Old days sorting style) Reverse order sorting can also be achieved by below line of code and it also produces the same output as above.
students.stream()
.sorted((o1, o2) -> o2.compareTo(o1))
.forEach(System.out::println);
#3 Sorting a custom object list. stream.sorted()
method is also applicable for custom class list object. Suppose we have Student
class and we want to sort all the students based on roll number.
package org.websparrow.sorting;
public class Student {
// Generate Getters and Setters...
private Integer rollNo;
private String firstName;
private String lastName;
public Student(Integer rollNo, String firstName, String lastName) {
super();
this.rollNo = rollNo;
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return "Student [rollNo=" + rollNo + ", firstName=" + firstName
+ ", lastName=" + lastName + "]";
}
}
package org.websparrow.sorting;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Java8Sorting3 {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student(31, "Abhinav", "Rathi"),
new Student(6, "Prince", "Agrahari"),
new Student(17, "Sandeep", "Jaiswal"),
new Student(25, "Gaurav", "Agrawal"));
System.out.println("==== BEFORE SORTING =====");
students.stream().forEach(System.out::println);
System.out.println("==== AFTER SORTING =====");
students.stream()
.sorted(Comparator.comparingInt(Student::getRollNo))
.forEach(System.out::println);
}
}
Output
==== BEFORE SORTING =====
Student [rollNo=31, firstName=Abhinav, lastName=Rathi]
Student [rollNo=6, firstName=Prince, lastName=Agrahari]
Student [rollNo=17, firstName=Sandeep, lastName=Jaiswal]
Student [rollNo=25, firstName=Gaurav, lastName=Agrawal]
==== AFTER SORTING =====
Student [rollNo=6, firstName=Prince, lastName=Agrahari]
Student [rollNo=17, firstName=Sandeep, lastName=Jaiswal]
Student [rollNo=25, firstName=Gaurav, lastName=Agrawal]
Student [rollNo=31, firstName=Abhinav, lastName=Rathi]
#4 Sorting a custom object list in reverse order based on roll number.
System.out.println("==== REVERSE ORDER =====");
students.stream()
.sorted(Comparator.comparingInt(Student::getRollNo).reversed())
.forEach(System.out::println);
System.out.println("==== REVERSE ORDER (Old days) =====");
students.stream()
.sorted((o1, o2) -> o2.getRollNo() - o1.getRollNo())
.forEach(System.out::println);
#5 Similarly, we can sort the custom object on different attributes like first name and last name.
System.out.println("==== AFTER SORTING =====");
students.stream()
.sorted(Comparator.comparing(Student::getFirstName))
.forEach(System.out::println);
System.out.println("==== AFTER SORTING (REVERSE ORDER) =====");
students.stream()
.sorted(Comparator.comparing(Student::getFirstName).reversed())
.forEach(System.out::println);
System.out.println("==== AFTER SORTING (Old days) =====");
students.stream()
.sorted((o1, o2) -> o1.getFirstName().compareTo(o2.getFirstName()))
.forEach(System.out::println);
References
- Interface Stream<T>
- Stream<T> sorted()
- Stream<T> sorted(Comparator<? super T> comparator)
- Interface Comparator<T>