Advanced Intermediate Operations: Sorting, Distinct, and Limiting

Advanced Intermediate Operations: Sorting, Distinct, and Limiting

In the previous lesson, you mastered intermediate operations like filtering and mapping streams, laying a solid foundation for stream manipulation in Java. Now, let's continue building on that knowledge by exploring sorting, removing duplicates, and limiting elements. These operations will enable you to perform more complex data transformations, making your code even more powerful and efficient.

What You'll Learn

By the end of this lesson, you'll be equipped to handle more advanced data manipulation scenarios using Java Streams.

  • How to sort elements within a stream.
  • How to remove duplicates using the distinct method.
  • How to limit and skip elements in a stream.

Transforming Data with Stream Operations

Stream operations allow you to perform complex data manipulations efficiently and concisely. By using methods like sorting, removing duplicates, and limiting elements, you can transform your streams into well-structured data ready for analysis or further processing. These operations are vital when handling data for tasks like organizing records, filtering results, or ensuring data integrity.

In the following sections, you'll learn how these operations can streamline data preparation, improve code readability, and help you tackle various data-related challenges in Java.

Sorting Elements

Sorting with streams is as easy as using the .sorted() method. Let's look at an example:

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

// Sorting the stream and printing
System.out.print("Sorted numbers: ");
numbers.stream()
       .sorted()
       .forEach(n -> System.out.print(n + " "));
System.out.println();

Output:

Sorted numbers: 1 2 2 3 3 4 5 

The sorted method sorts the elements in their natural order. In this example, the numbers are sorted in ascending order and printed out. For custom orders, you can pass comparators as an argument to the sorted method.

Here's an example of sorting the numbers in descending order using a comparator:

// Sorting the stream in descending order and printing
System.out.print("Sorted numbers (descending): ");
numbers.stream()
       .sorted(Comparator.reverseOrder())
       .forEach(n -> System.out.print(n + " "));
System.out.println();

Comparator.reverseOrder() is a comparator that imposes the reverse of the natural ordering of the elements. This means that the elements will be sorted in descending order.

Output:

Sorted numbers (descending): 5 4 3 3 2 2 1 

Sorting is useful when you need an ordered dataset for further use or display.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal