Core Java

Java 8 Stream sorted()

Introduction:

Java 8 Stream API is a powerful way to achieve functional programming. In this post, we’ll learn about Java 8 Stream sorted() method by looking at some good examples.

In case you wish to learn more about Java 8 Streams API in general, we’ll suggest you read this article.

Signature:

There are two variants of sorted() method:

//Elements sorted according to their natural order
Stream<T> sorted()

//Elements sorted using the given comparator
Stream<T> sorted(Comparator<? super T> comparator)

First is the very basic one, which sorts the elements in a stream based on their natural order. The other uses the provided Comparator for sorting elements. In Java 8, we can use a lambda expression to provide our implementation of the Comparator.

sorted() Method:

Let’s first learn to use the most basic variant:

List<Integer> numbers = Arrays.asList(4, 1, 3, 5, 2);

numbers.stream().sorted().forEach(System.out::println);

As expected, the above code will print below output:

1
2
3
4
5

What if we sort a list of Strings?

List<String> names = Arrays.asList("Sam", "Ray", "John", "Joseph", "Sierra"); 

names.stream().sorted().forEach(System.out::println);

Yes, you guessed it right, they’ll be sorted alphabetically:

John
Joseph
Ray
Sam
Sierra

sorted(Comparator comparator) Method:

What if we want to sort our elements in reverse order? Or what if we want to sort a stream of our custom objects? For such cases, we can optionally choose to pass-in our Comparator implementation to the method argument.

1.) Sorting In Reverse Order:

Let’s say we wish to sort our stream of numbers in reverse order. For that, we can use in-built Comparator.reverseOrder() implementation of Comparator to achieve it:

numbers.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);

The above code will print numbers 5 to 1 in reverse order.

2.)Sorting a Stream Of Custom Objects:

Let’s say we maintain a List<Student> of students:

List<Student> students = new ArrayList<>();
students.add(new Student(1, "Sam"));
students.add(new Student(3, "Sierra"));
students.add(new Student(2, "Ray"));
students.add(new Student(4, "John"));

System.out.println(students); // prints [{1:Sam}, {3:Sierra}, {2:Ray}, {4:John}]

Where,

class Student {
    private int id;
    private String name;

    //constructor, getters, setters
    public String toString(){
        return "{"+ id+":"+name+"}";
    } 
}

Now let’s try to sort a stream over this List<Student> in variousĀ  ways and print its contents:

//prints {1:Sam}{2:Ray}{3:Sierra}{4:John}
students.stream()
    .sorted(Comparator.comparing(Student::getId))
    .forEach(System.out::print);

//prints {4:John}{3:Sierra}{2:Ray}{1:Sam}
students.stream()
    .sorted(Comparator.comparing(Student::getId).reversed())
    .forEach(System.out::print);

//prints {3:Sierra}{1:Sam}{4:John}{2:Ray} :: Sorting based on Last Character of names of Students
students.stream().sorted((s1, s2) ->
                           Character.compare(s1.getName().charAt(s1.getName().length()  - 1),
                                             s2.getName().charAt(s2.getName().length() - 1)))
                  .forEach(System.out::print);

The first example sorts the stream contents using the id in ascending order. The next one sorts the stream contents using id but in reverse order.

The last example is comparatively trickier as it sorts our stream based on the last character comparison of student names in our List.

Conclusion:

In this tutorial, we learned the usage of sorted() method over Streams in Java. We learned sorting elements in both ascending as well as descending orders. We also learned to sort our stream over a List/Set of custom objects.

However, it’s important to remember that this method only sorts the contents of the stream and not the actual data structure which holds the contents. So in all our examples, the contents of our List remained as-is.

 

Be the First to comment.

Leave a Comment

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