Skip to lesson

limit(n) keeps only the first n elements of a stream, and skip(n) throws away the first n and keeps the rest. Together they answer two everyday questions: "show me the top 10" and "show me page 3".

limit and skip, one element at a time

limit(n) keeps at most the first n elements and then stops the stream. It is short-circuiting: once it has enough, the steps before it are not asked for any more.

limit(n) lets the first n elements through and then stops the stream: it is short-circuiting. skip(n) is the mirror image: it drops the first n elements and passes on the rest.

Example 1 · limit and skip on a short list

LimitSkipDemo.javaJava
import java.util.List;
public class LimitSkipDemo {    public static void main(String[] args) {        List<String> queue = List.of("Asha", "Ravi", "Meena", "Kiran", "Arjun", "Zoya", "Dev");
        System.out.println("limit(3):  " + queue.stream().limit(3).toList());        System.out.println("skip(3):   " + queue.stream().skip(3).toList());        System.out.println("limit(10): " + queue.stream().limit(10).toList());        System.out.println("skip(10):  " + queue.stream().skip(10).toList());
        try {            queue.stream().limit(-1).toList();        } catch (IllegalArgumentException e) {            System.out.println("limit(-1): " + e.getMessage());        }    }}
Output
limit(3):  [Asha, Ravi, Meena]
skip(3):   [Kiran, Arjun, Zoya, Dev]
limit(10): [Asha, Ravi, Meena, Kiran, Arjun, Zoya, Dev]
skip(10):  []
limit(-1): -1

What this code does

  • limit(3) keeps positions 1 to 3, and skip(3) keeps everything from position 4. Asking for more than there is gives all seven, and skipping more than there is gives an empty list.
  • Only a negative count is an error. The message names the bad value.

With limit, the rest of the data is never even read. If the stream has fewer than n elements, you simply get all of them. If the stream has n elements or fewer, skip(n) gives an empty result, not an error.

Both count positions, not values, and both keep the original order. A negative argument, such as limit(-1), throws an IllegalArgumentException.

Top N results: sort, then limit

A results page shows the top 3 scorers. The loop way is to copy the list, sort the copy, then loop from 0 to 3 while also checking that i stays below the size.

Example 2 · Top 3 scorers: loop versus sorted then limit

TopThreeDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
record Student(String name, int marks) {}
public class TopThreeDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", 78), new Student("Ravi", 91), new Student("Meena", 66),                new Student("Kiran", 85), new Student("Arjun", 95), new Student("Zoya", 72));
        Comparator<Student> highFirst = Comparator.comparing(Student::marks).reversed();
        List<Student> copy = new ArrayList<>(students);        copy.sort(highFirst);        System.out.print("Loop:   ");        for (int i = 0; i < 3 && i < copy.size(); i++) {            System.out.print(copy.get(i).name() + " ");        }        System.out.println();
        List<String> top3 = students.stream()                .sorted(highFirst)                .limit(3)                .map(Student::name)                .toList();        System.out.println("Stream: " + top3);    }}
Output
Loop:   Arjun Ravi Kiran
Stream: [Arjun, Ravi, Kiran]

What this code does

  • The loop needs a copy (so the original is not reordered), a sort, and a double check i < 3 && i < copy.size().
  • The pipeline says the same thing in order: best first, keep 3, take the names. map comes after limit, so only 3 names are built.
  • Why: both sort once, so the cost is the same. The stream drops the copy and the index check, which is where loop bugs hide.

The stream way states the two ideas in order: put the best first, then keep three. students.stream().sorted(byMarksHighFirst).limit(3). If the class has only two students, limit(3) gives two, with no index check to forget. The same pattern gives the 5 newest orders, the 10 cheapest flights, or the 3 slowest API calls: sort by the right key in the right direction, then limit.

Paging with skip and limit

Apps never send 10,000 products at once. An API returns one page, say 20 items, and the app asks for page 1, page 2, page 3 as you scroll. The page number and page size arrive with the request, as in /products?page=3&size=20.

  1. Sort first, so every page uses the same order. Without a fixed order, an item could appear on two pages or on none.
  2. Work out how many items come before the page: (page - 1) * size.
  3. Call skip with that number, then limit(size).
  4. The last page may be short, and a page past the end is empty. Both are normal results, not errors.

Example 3 · Paging: page 1, 2, 3 and past the end

PagingDemo.javaJava
import java.util.List;
public class PagingDemo {    static List<String> page(List<String> items, int pageNo, int size) {        return items.stream()                .sorted()                .skip((long) (pageNo - 1) * size)                .limit(size)                .toList();    }
    public static void main(String[] args) {        List<String> products = List.of("Pen", "Bag", "Lamp", "Mouse", "Bottle", "Cable",                "Diary", "Fan", "Glue", "Ink");
        for (int p = 1; p <= 5; p++) {            System.out.println("Page " + p + ": " + page(products, p, 3));        }    }}
Output
Page 1: [Bag, Bottle, Cable]
Page 2: [Diary, Fan, Glue]
Page 3: [Ink, Lamp, Mouse]
Page 4: [Pen]
Page 5: []

What this code does

  • Each page skips (pageNo - 1) * size items and takes the next size. Page 3 skips 6 and shows items 7 to 9.
  • With 10 products and 3 per page, page 4 has one item and page 5 is empty. Sorting first gives every page the same fixed order. The (long) cast avoids int overflow for very large page numbers.

Example 4 · skip then limit versus limit then skip

OrderMattersDemo.javaJava
import java.util.List;
public class OrderMattersDemo {    public static void main(String[] args) {        List<Integer> positions = List.of(1, 2, 3, 4, 5, 6, 7, 8);
        System.out.println("skip(2).limit(3): " + positions.stream().skip(2).limit(3).toList());        System.out.println("limit(3).skip(2): " + positions.stream().limit(3).skip(2).toList());        System.out.println("limit(5).skip(2): " + positions.stream().limit(5).skip(2).toList());    }}
Output
skip(2).limit(3): [3, 4, 5]
limit(3).skip(2): [3]
limit(5).skip(2): [3, 4, 5]

What this code does

  • skip(2).limit(3) drops 1 and 2, then keeps the next three: 3, 4, 5.
  • limit(3).skip(2) first keeps 1, 2, 3, then drops two of those, leaving only 3. limit(5).skip(2) is another way to write positions 3 to 5.

To get page p (counting from 1) of size s, skip the items on all earlier pages, then take one page: .skip((long) (p - 1) * s).limit(s). For page 3 of size 20 that is skip(40).limit(20): items 41 to 60.

Order matters, and the limit-before-sorted trap

Steps run in the order you write them. skip(2).limit(3) drops 2 and then keeps the next 3, which are positions 3 to 5. limit(3).skip(2) keeps positions 1 to 3 and then drops 2 of those, leaving only position 3.

Marks in list order: Asha 78, Ravi 91, Meena 66, Kiran 85, Arjun 95, Zoya 72. limit(3) then sorted keeps only the first three, giving Ravi 91, Asha 78, Meena 66. sorted then limit(3) gives the top three: Arjun 95, Ravi 91, Kiran 85.

Example 5 · Trap: limit before sorted gives the wrong top 3

WrongTopDemo.javaJava
import java.util.Comparator;import java.util.List;
record Student(String name, int marks) {}
public class WrongTopDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", 78), new Student("Ravi", 91), new Student("Meena", 66),                new Student("Kiran", 85), new Student("Arjun", 95), new Student("Zoya", 72));        Comparator<Student> highFirst = Comparator.comparing(Student::marks).reversed();
        System.out.print("limit then sorted: ");        students.stream()                .limit(3)                .sorted(highFirst)                .forEach(s -> System.out.print(s.name() + " " + s.marks() + "  "));        System.out.println();
        System.out.print("sorted then limit: ");        students.stream()                .sorted(highFirst)                .limit(3)                .forEach(s -> System.out.print(s.name() + " " + s.marks() + "  "));        System.out.println();    }}
Output
limit then sorted: Ravi 91  Asha 78  Meena 66
sorted then limit: Arjun 95  Ravi 91  Kiran 85

What this code does

  • The wrong version takes the first 3 students in list order (Asha, Ravi, Meena) and sorts only them. It looks sorted, but Arjun with 95 is missing.
  • Sorting first puts the real toppers at the front, and then limit(3) keeps them.

Example 6 · limit stops the work early

ShortCircuitDemo.javaJava
import java.util.List;
public class ShortCircuitDemo {    public static void main(String[] args) {        List<Integer> orderAmounts = List.of(1200, 300, 4500, 800, 2600, 150, 9900);
        List<Integer> firstTwoBig = orderAmounts.stream()                .filter(a -> {                    System.out.println("checking " + a);                    return a >= 1000;                })                .limit(2)                .toList();        System.out.println("First two big orders: " + firstTwoBig);    }}
Output
checking 1200
checking 300
checking 4500
First two big orders: [1200, 4500]

What this code does

  • Once limit(2) has two elements, it stops asking for more. The filter never checks 800, 2600, 150 or 9900.
  • This is short-circuiting. On a log with millions of lines, limit saves reading everything after the matches you need. The print in filter is only there to trace the flow.

The most common bug is limit before sorted: .limit(3).sorted(...) takes the first 3 elements in the list's order, then sorts just those 3.

Read the pipeline top to bottom and ask what the stream holds after each step. The code runs and prints three neatly sorted names, so the bug is easy to miss, but they are not the top 3. For the top N, sorted must come first.

Predict the output

Which order wins?

Read the code, then pick what it prints.

Round 1 of 2

List<Integer> marks = List.of(55, 90, 72, 88, 40);
System.out.println(marks.stream().sorted(Comparator.reverseOrder()).limit(3).toList());
System.out.println(marks.stream().limit(3).sorted(Comparator.reverseOrder()).toList());
Rule of thumb: decide what "first" means (sort), then count (skip and limit).

Next step

Check your understanding

12 quick questions