sorted(), distinct(), and limit() Stream Operations
Fast recall
Quick revision
Core answer
sorted() is a stateful intermediate operation that orders elements naturally or with a Comparator. distinct() keeps distinct elements according to equals; for an ordered stream it is stable, while an unordered stream need not preserve a particular duplicate. limit(n) keeps at most the first n elements in encounter order when one exists and rejects a negative n.Knowledge of common intermediate operations for stream manipulation—these are practical operations used frequently in real code.
Not knowing sorted() accepts a Comparator for custom ordering, or not understanding distinct() uses equals/hashCode so objects need proper implementations.
Show a realistic pipeline combining multiple operations in logical order—like filtering data, removing duplicates, sorting, and limiting results for a paginated API response.
Interview-ready guide
Interview answer
sorted orders elements naturally or with a Comparator and is stateful: a finite stream must provide all upstream elements before the sorted result can begin. distinct removes elements that are equal according to equals; it keeps the first equal element only when the stream is ordered. limit(n) keeps at most the first n encountered elements and can stop early.
For a global top-five list, filter irrelevant values, apply any deduplication required by the domain, sort the remaining values, and then limit to five. If limit comes before sort, Java sorts only the first five upstream elements; they are not random when the source has encounter order, but they are not necessarily the global top five. There is no universal best order for every pipeline because moving map or distinct can change the meaning.
sorted(), distinct(), and limit() Stream Operations
Direct Answer
sorted() is a stateful intermediate operation that orders elements naturally or with a Comparator. distinct() keeps distinct elements according to equals; for an ordered stream it is stable, while an unordered stream need not preserve a particular duplicate. limit(n) keeps at most the first n elements in encounter order when one exists and rejects a negative n.
Code Example
record Product(String id, String name, double price, String category) {}
class ProductService {
public List<Product> getTopExpensiveUniqueProducts(List<Product> products, int count) {
return products.stream()
.filter(p -> p.price() > 0) // Remove invalid prices
.distinct() // Remove duplicates
.sorted(Comparator.comparingDouble(Product::price) // Sort by price
.reversed()) // High to low
.limit(count) // Take top N
.collect(Collectors.toList());
}
public List<String> getTopCategoriesByName(List<Product> products) {
return products.stream()
.map(Product::category)
.distinct() // Unique categories
.sorted() // Natural order (alphabetical)
.limit(5)
.collect(Collectors.toList());
}
public List<Product> getAffordableProductsSorted(List<Product> products, double maxPrice) {
return products.stream()
.filter(p -> p.price() <= maxPrice)
.sorted(Comparator.comparing(Product::name)) // Custom Comparator
.collect(Collectors.toList());
}
}
Common Mistakes & Pitfalls
- Natural sorting a non-Comparable type: use a suitable
Comparator; otherwise evaluation may throwClassCastException. - Breaking the equality contract:
distinctuses equality semantics. Value types should implement consistentequalsandhashCode; identity equality may be correct for some domain objects, so do not override blindly. - Calling the limited subset the global top N:
limitbeforesortedselects the first N upstream elements and only then sorts that subset. - Treating one operation order as universally optimal: filtering early often helps, but moving a transformation or distinct stage can change what is being compared and therefore change the answer.
Check your understanding
Answer these without looking back at the article.
- What is the difference between limit() and skip()?
- Is sorted() a stateful or stateless operation?
- How does distinct() work for custom objects?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.