How to take the first N elements
Short answer
limit() keeps the first N elements of the stream:
void main() {
var scores = List.of(95, 88, 76, 64, 51);
IO.println(scores.stream().limit(3).toList());
}Output:
[95, 88, 76]The top after sorting
Together with sorted() you get "the top three":
void main() {
var scores = List.of(64, 95, 51, 88, 76);
IO.println(scores.stream().sorted(Comparator.reverseOrder()).limit(3).toList());
}Output:
[95, 88, 76]Skipping elements
skip() drops the first N elements:
void main() {
var lines = List.of("header", "row 1", "row 2");
IO.println(lines.stream().skip(1).toList());
}Output:
[row 1, row 2]While a condition holds
takeWhile() takes elements while the condition is true and stops at the first one that fails:
void main() {
var temperatures = List.of(12, 15, 18, 9, 20);
IO.println(temperatures.stream().takeWhile(t -> t > 10).toList());
}Output:
[12, 15, 18]Common mistake
Taking subList(0, n) of a list shorter than n. Unlike limit(), subList() does not forgive going out of bounds:
void main() {
var scores = List.of(95, 88);
IO.println(scores.stream().limit(3).toList());
IO.println(scores.subList(0, 3));
}Output:
[95, 88]
Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 3Functions used in this recipe
- Stream.limit() — Truncates a stream to its first N elements.
- Stream.skip() — Skips the first N elements of a stream.
- Stream.takeWhile() — Takes elements while a condition holds and stops at the first one that fails it.
- List.subList() — Returns the part of a list between two indexes.