Sub topic 8
Sorting, Removing Duplicates, and Limiting
The filter and map operations let you choose elements and change them. Real programs often need a few more steps: put the results in order, remove repeats, or keep only the first few. The Stream API has four intermediate operations for these jobs: sorted, distinct, limit, and skip.
An intermediate operation is a step in the middle of a pipeline. It returns a new stream, so you can add more steps after it. All four operations in this chapter work that way.
| Operation | What it does | Example result for `[3, 1, 3, 2]` |
|---|---|---|
| `sorted()` | Puts elements in natural order | `[1, 2, 3, 3]` |
| `sorted(comparator)` | Puts elements in the order you choose | `[3, 3, 2, 1]` with `Comparator.reverseOrder()` |
| `distinct()` | Removes repeated elements | `[3, 1, 2]` |
| `limit(n)` | Keeps only the first `n` elements | `limit(2)` gives `[3, 1]` |
| `skip(n)` | Throws away the first `n` elements | `skip(2)` gives `[3, 2]` |
Sorting with sorted
Natural order
Natural order is the order a type already knows about. Numbers go from small to large. Strings go in alphabetical order, with upper-case letters before lower-case ones. A type has a natural order when it implements Comparable, which is an interface that says "I know how to compare myself to another object of my type."
Calling sorted() with no arguments uses natural order.
Your own order with a Comparator
A Comparator is an object that decides which of two elements comes first. You pass one to sorted when you want a different order. The Comparator class has helper methods that build comparators for you:
Comparator.reverseOrder()reverses natural order.Comparator.comparing(keyFunction)sorts by a key, such as a string's length..reversed()flips any comparator..thenComparing(...)breaks ties when two elements have the same key.
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortedExample {
public static void main(String[] args) {
List<String> fruits = List.of("pear", "apple", "fig", "banana");
List<String> natural = fruits.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(natural); // [apple, banana, fig, pear]
List<String> reversed = fruits.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println(reversed); // [pear, fig, banana, apple]
List<String> byLength = fruits.stream()
.sorted(Comparator.comparing(String::length))
.collect(Collectors.toList());
System.out.println(byLength); // [fig, pear, apple, banana]
List<String> longestFirst = fruits.stream()
.sorted(Comparator.comparing(String::length).reversed())
.collect(Collectors.toList());
System.out.println(longestFirst); // [banana, apple, pear, fig]
}
}Breaking ties
Sometimes two elements have the same sort key. In the list below, "kiwi", "pear", and "plum" all have length 4. Use thenComparing to say what happens next. Here, words of the same length are put in alphabetical order.
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class TieBreakExample {
public static void main(String[] args) {
List<String> words = List.of("plum", "apple", "pear", "fig", "kiwi");
List<String> result = words.stream()
.sorted(Comparator.comparing(String::length)
.thenComparing(Comparator.naturalOrder()))
.collect(Collectors.toList());
System.out.println(result); // [fig, kiwi, pear, plum, apple]
}
}Without the tie-breaker, the sort is stable. A stable sort keeps tied elements in the order they had in the source. That means you would get [fig, plum, pear, kiwi, apple].
Removing duplicates with distinct
distinct() keeps the first time each value appears and drops any later copies. It does not change the order of the elements it keeps.
To decide whether two elements are the same, distinct uses the equals and hashCode methods. Strings, numbers, and records already have these methods. Your own classes need them too, or every object will count as different.
import java.util.List;
import java.util.stream.Collectors;
public class DistinctExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(3, 1, 3, 2, 1);
List<Integer> unique = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(unique); // [3, 1, 2]
List<String> tags = List.of("Java", "java", "JAVA", "Stream");
List<String> uniqueIgnoringCase = tags.stream()
.map(String::toLowerCase)
.distinct()
.collect(Collectors.toList());
System.out.println(uniqueIgnoringCase); // [java, stream]
}
}The second example shows a common trick. To remove duplicates while ignoring case, first map every element to the same form, then call distinct.
Keeping or skipping elements with limit and skip
limit(n) keeps the first n elements and ignores the rest. skip(n) throws away the first n elements and keeps the rest. Both take a long number. A negative number throws an IllegalArgumentException.
If the stream has fewer elements than n, nothing goes wrong. limit(10) on a three-element stream gives all three. skip(10) on a three-element stream gives an empty stream.
Used together, skip and limit make paging. Paging means showing results one page at a time, like search results. To get page p (counting from 0) with size items per page, skip p * size items and then limit to size.
import java.util.List;
import java.util.stream.Collectors;
public class PagingExample {
static List<Integer> page(List<Integer> items, int pageNumber, int pageSize) {
return items.stream()
.skip((long) pageNumber * pageSize)
.limit(pageSize)
.collect(Collectors.toList());
}
public static void main(String[] args) {
List<Integer> items = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println(page(items, 0, 3)); // [1, 2, 3]
System.out.println(page(items, 1, 3)); // [4, 5, 6]
System.out.println(page(items, 3, 3)); // [10]
System.out.println(page(items, 4, 3)); // []
}
}Putting them together: order matters
These operations are often used together. A classic task is "top three": find the three highest unique scores.
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class TopThreeExample {
public static void main(String[] args) {
List<Integer> scores = List.of(70, 95, 82, 95, 60, 88, 82);
List<Integer> topThree = scores.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.limit(3)
.collect(Collectors.toList());
System.out.println(topThree); // [95, 88, 82]
List<Integer> wrongOrder = scores.stream()
.limit(3)
.distinct()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println(wrongOrder); // [95, 82, 70]
}
}The second pipeline uses the same steps in a different order and gives a wrong answer. It cuts the list down to the first three scores, 70, 95, 82, before sorting. Steps run in the order you write them. Ask yourself what each step receives from the step before it.
Without distinct, the first pipeline would return [95, 95, 88], because the score 95 appears twice.
Stateful operations
filter and map look at one element at a time. They are stateless, which means they remember nothing about other elements. The operations in this chapter are different:
sortedmust see every element before it can output the first one. On a huge stream this uses a lot of memory, and on an endless stream it never finishes.distinctremembers every value it has seen so it can spot repeats.limitandskipcount how many elements have passed.
Operations that remember things like this are called stateful. The chapters on lazy evaluation and infinite streams explain why limit is the key that makes endless streams usable. For now, remember this rule: put filter before sorted when you can, so there are fewer elements to sort.
Exercise
Given List.of("delta", "alpha", "charlie", "alpha", "bravo", "delta"), write a pipeline that returns the second and third names in alphabetical order with no duplicates. What list does it print?
Show answer
names.stream().distinct().sorted().skip(1).limit(2).collect(Collectors.toList()). After distinct the names are delta, alpha, charlie, bravo. After sorted they are alpha, bravo, charlie, delta. skip(1) drops alpha and limit(2) keeps the next two, so it prints [bravo, charlie].
Exercise
What does List.of(5, 3, 8, 1).stream().limit(2).sorted().collect(Collectors.toList()) print, and why is the result not [1, 3]?
Show answer
It prints [3, 5]. limit(2) runs first and keeps only 5 and 3, then sorted puts those two in order. To get the two smallest values, [1, 3], call sorted() before limit(2).
Exercise
You have a class Book with a getTitle() method that returns a String, and Book does not implement Comparable. What happens if you call books.stream().sorted(), and how do you sort the books by title instead?
Show answer
The code compiles, but it throws a ClassCastException at run time because Book has no natural order. Pass a comparator instead: books.stream().sorted(Comparator.comparing(Book::getTitle)).