Stream Sorted, Distinct, Limit and Skip

Naveen AnamaneniUpdated · 4 min read
easyJava 25javastreams

Besides filtering and transforming, streams have operations that shape the sequence: sorted puts elements in order, distinct removes duplicates, limit keeps the first few, skip drops the first few, and takeWhile and dropWhile (Java 9) keep or drop elements while a condition holds. In this lesson, you will learn each of these operations and how to combine them, for example to show one "page" of results.

Methods

MethodDescription
sorted()It sorts the elements in natural order.
sorted(Comparator c)It sorts the elements with a comparator.
distinct()It removes duplicates, using equals.
limit(long n)It keeps only the first n elements.
skip(long n)It drops the first n elements.
takeWhile(Predicate p)It keeps elements until the first one that fails the test.
dropWhile(Predicate p)It drops elements until the first one that fails the test, then keeps the rest.

Example: sorted and distinct

Let's see an example that sorts and removes duplicates.

SortDistinct.java▶ Try it
import java.util.Comparator;
import java.util.List;
 
public class SortDistinct {
    public static void main(String[] args) {
        List<Integer> marks = List.of(85, 91, 78, 91, 60, 85);
 
        System.out.println(marks.stream().distinct().toList());
        System.out.println(marks.stream().sorted().toList());
        System.out.println(marks.stream().distinct()
            .sorted(Comparator.reverseOrder()).toList());
 
        List<String> names = List.of("Srihitha", "Navika", "Advitha");
        System.out.println(names.stream()
            .sorted(Comparator.comparing(String::length))
            .toList());
    }
}
Output
[85, 91, 78, 60]
[60, 78, 85, 85, 91, 91]
[91, 85, 78, 60]
[Navika, Advitha, Srihitha]

Explanation: distinct keeps the first occurrence of each value in its original order. sorted() uses natural order; sorted(Comparator.reverseOrder()) sorts from highest to lowest. The last pipeline sorts names by length.

Example: limit and skip for Paging

Paging.java▶ Try it
import java.util.List;
import java.util.stream.IntStream;
 
public class Paging {
    public static void main(String[] args) {
        List<Integer> items = IntStream.rangeClosed(1, 10).boxed().toList();
        int pageSize = 3;
 
        for (int page = 1; page <= 4; page++) {
            List<Integer> onPage = items.stream()
                .skip((long) (page - 1) * pageSize)
                .limit(pageSize)
                .toList();
            System.out.println("Page " + page + ": " + onPage);
        }
    }
}
Output
Page 1: [1, 2, 3]
Page 2: [4, 5, 6]
Page 3: [7, 8, 9]
Page 4: [10]

Explanation: For each page, skip jumps over the items of the earlier pages, and limit takes at most one page of items. The last page has only one item left.

Example: takeWhile and dropWhile

WhileOps.java▶ Try it
import java.util.List;
 
public class WhileOps {
    public static void main(String[] args) {
        List<Integer> temps = List.of(18, 21, 24, 31, 22, 35);
 
        System.out.println("takeWhile < 30: "
            + temps.stream().takeWhile(t -> t < 30).toList());
        System.out.println("dropWhile < 30: "
            + temps.stream().dropWhile(t -> t < 30).toList());
        System.out.println("filter    < 30: "
            + temps.stream().filter(t -> t < 30).toList());
    }
}
Output
takeWhile < 30: [18, 21, 24]
dropWhile < 30: [31, 22, 35]
filter    < 30: [18, 21, 24, 22]

Explanation: takeWhile stops at 31, the first value that fails, even though 22 later passes. dropWhile drops values until 31, then keeps everything after it. filter checks every element, so it includes 22.

Common Mistakes

Using distinct on objects without equals and hashCode. Duplicates aren't detected; records are fine.

Calling limit before sorted when you want the top values. Sort first, then limit.

Expecting takeWhile to behave like filter. It stops at the first failure.

Practice

  1. Easy: From a list of 10 scores, print the top three distinct scores.
  2. Harder: Given a sorted list of timestamps (as integers), use dropWhile and takeWhile to keep only those between 100 and 200.

Quick check: Sorted, distinct, limit, skip

4 questions
1What does distinct use to find duplicates?
2Which pipeline gives page 2 with 5 items per page?
3For [1, 2, 9, 3], what does takeWhile(x -> x < 5) return?
4For [1, 2, 9, 3], what does dropWhile(x -> x < 5) return?

Key Takeaways

Was this tutorial helpful?

Lesson 319 of 482