sorted, distinct, limit, skip

Streams · lesson 6 of 42 · 3 min read

Order, de-duplicate and page a stream, and know which of these ops cost memory.

Open this lesson in the learning hub

Key points

  • distinct compares with equals and hashCode. Records get both for free.
  • sorted() needs Comparable elements. sorted(comparator) works for anything.
  • Build orders with Comparator.comparing(...), then .thenComparing(...) and .reversed().
  • skip(n).limit(m) is paging. The order of those two calls matters.
  • sorted and distinct are stateful: they buffer elements, so they cost memory on large streams.
  • limit and skip are cheap on ordered sources but get expensive on parallel streams.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> names = List.of("ada", "grace", "ada", "alan", "barbara", "grace", "linus");

        System.out.println("distinct : " + names.stream().distinct().toList());
        System.out.println("sorted   : " + names.stream().distinct().sorted().toList());
        System.out.println("reverse  : " + names.stream().distinct().sorted(Comparator.reverseOrder()).toList());
        System.out.println("byLength : " + names.stream().distinct()
                .sorted(Comparator.comparingInt(String::length)).toList());
        System.out.println("limit 3  : " + names.stream().distinct().sorted().limit(3).toList());
        System.out.println("skip 2   : " + names.stream().distinct().sorted().skip(2).toList());
        System.out.println("page 2   : " + names.stream().distinct().sorted().skip(2).limit(2).toList());
    }
}

sorted and distinct must see everything; limit and skip let the stream stop early.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Streams course, and every lesson in it is listed on the Streams contents page.