Video in progress
What do the distinct(), limit() and skip() operations do?
distinct() removes duplicate elements by equals, limit(n) keeps only the first n, and skip(n) discards the first n. All three are intermediate.
📖 Answer
List<Integer> nums = List.of(5, 3, 5, 1, 3, 8, 9, 2);
nums.stream().distinct().toList(); // [5, 3, 1, 8, 9, 2]
nums.stream().skip(2).limit(3).toList(); // [5, 1, 3]
skip + limit is simple pagination for an in-memory list:
int page = 2, size = 20;
List<Product> pageItems = products.stream()
.skip((long) page * size)
.limit(size)
.toList();
But don't do this for data in a database: pulling every row into memory and then trimming is wasteful. There you need SQL's LIMIT/OFFSET or Spring's Pageable.
distinct relies on the element's equals and hashCode. If they aren't written in your own class, objects that look identical won't be removed. Records don't have this problem.
limit is the simplest way to stop an infinite stream: Stream.generate(...).limit(10).
Sign up to mark studied questions and save your progress.