The Java Stream API is a powerful tool for processing collections in a functional style. In this article, we’ll explore how to use key stream operations like skip()
, limit()
, max()
, min()
, and filtering with Optional
through a list of sample Product
objects.
This example is perfect for learning how to manipulate and query collections in a concise and expressive way.
Example Code and Explanation
Let’s walk through each block of code and explain what it does.
1️⃣ Skip the First Three Entries
java
System.out.println("****Before Skip the first three entries from collection***");
List<Product> beforeSkipping = productList.stream().toList();
beforeSkipping.forEach(System.out::println);
System.out.println("**** After Skip the first three entries from collection***");
List<Product> skipFirstThree = productList.stream()
.skip(3)
.toList();
skipFirstThree.forEach(System.out::println);
- What it does: The
skip(3)
operation ignores the first three elements in the stream and returns the rest. - Use case: Useful for implementing pagination or ignoring certain items in a result set.
2️⃣ Limit to the First Three Entries
java
System.out.println("****Before Limit the first three entries from collection***");
List<Product> beforeLimitLastThree = productList.stream().toList();
beforeLimitLastThree.forEach(System.out::println);
System.out.println("**** After Limit the first three entries from collection***");
List<Product> AfterLimitLastThree = productList.stream()
.limit(3)
.toList();
AfterLimitLastThree.forEach(System.out::println);
- What it does: The
limit(3)
operation returns a stream of only the first three products. - Use case: Great for previews, top picks, or first-page results.
3️⃣ Find the Product with Maximum Units Sold
java
System.out.println("****Find a maximum value in a collection***");
Product findMaxNumberOfProductSold = productList.stream()
.max(Comparator.comparing(Product::getNumberOfProductSold))
.orElse(new Product());
System.out.println(findMaxNumberOfProductSold);
- What it does: Finds the product with the highest number of units sold using a comparator.
- Safe fallback: If the list is empty, it returns a default Product instance using
orElse(new Product())
. - Use case: Useful for leaderboard-type features or highlighting bestsellers.
4️⃣ Find the Product with the Minimum Rating
java
System.out.println("****Find a minimum rated in a collection***");
Product findMinimumRatedProduct = productList.stream()
.min(Comparator.comparing(Product::getItemRating))
.orElse(new Product());
System.out.println(findMinimumRatedProduct);
- What it does: Uses
min()
to find the product with the lowest customer rating. - Safe fallback: Also includes a default product in case the list is empty.
- Use case: Useful for quality analysis or identifying low-performing products.
5️⃣ Conditionally Find a Minimum Rated Product with Rating < 4
java
System.out.println("****Find a minimum rated in a collection with rating less than 4***");
Optional<Product> findMinimumRatedProductWithRatingLessThan4 = productList.stream()
.min(Comparator.comparing(Product::getItemRating))
.filter(m -> m.getItemRating() < 4);
System.out.println(findMinimumRatedProductWithRatingLessThan4.isPresent());
- What it does:
- First, finds the product with the lowest rating.
- Then applies a
filter()
to keep it only if the rating is less than 4. - Result: Since this may or may not return a result, it's wrapped in an
Optional
. - Use case: Helps with validations or flagging unacceptable ratings.
Summary of Operations
OperationPurposeMethod UsedSkip entriesIgnore the first N itemsstream().skip(n)
Limit entriesRestrict result to the first N itemsstream().limit(n)
Find maximumFind the item with the highest valuestream().max(...)
Find minimumFind the item with the lowest valuestream().min(...)
Optional with filterApply additional conditions to a result.filter(...)
Conclusion
This example clearly demonstrates the flexibility and expressiveness of Java's Stream API. Whether you're filtering out unwanted elements, paginating results, or extracting extreme values, these stream methods make the code more readable and concise.
If you’re building a recommendation engine, a dashboard, or doing any sort of analytics — these stream operations are must-know tools in your Java toolkit.