DEV Community

Kowsik Ratnagiri
Kowsik Ratnagiri

Posted on

🚀 🧠 Java Stream API Practice Guide – Concepts and Real-World Use Cases

Java Streams are a powerful way to process data declaratively. But many developers don’t go beyond basic map and filter. Here's a complete list of Stream API methods you should practice, from beginner to advanced — with real-world use cases.

🔹 1. map()
What it does: Transforms each element in a stream.
Use case: Extract names from a list of employees.

🔹2. filter()
What it does: Removes elements based on a condition.
Use case: Select developers with salary > ₹1,00,000.

🔹3. flatMap()
What it does: Flattens nested collections into a single stream.
Use case: Combine all skills from a list of developers (each with their own list).

🔹 4. collect()
What it does: Terminal operation to accumulate stream results.
Common collectors:

1.toList(), toSet(), toMap()

2.joining()

3.groupingBy(), partitioningBy()

4.reducing(), summarizingDouble()

🔹5. toMap()
What it does: Creates a map from stream data.
Use case: Map developer names to their salaries.
Handles duplicate keys with merge logic.

🔹 6. groupingBy()
What it does: Groups elements by a classifier function.
Use case: Group employees by department or projects by domain.
Can be combined with counting(), mapping(), maxBy(), averagingDouble().

🔹7. partitioningBy()
What it does: Splits elements into two groups (true/false).
Use case: Partition users into active and inactive.

🔹 8. reduce()
What it does: Combines elements into a single result.
Use case: Calculate total salary or find the longest name.

🔹9. distinct()
What it does: Removes duplicates.
Use case: Get unique technologies used in all projects.

🔹10. sorted()
What it does: Sorts the stream.
Use case: Sort developers by salary or age.

🔹 11. limit() / skip()
What it does: Pagination-style control.
Use case: Get top 5 earners, skip first 10 results.

🔹 12. anyMatch(), allMatch(), noneMatch()
What it does: Test if elements match a condition.
Use case: Check if any developer uses “Docker”.

🔹 13. findFirst() / findAny()
What it does: Terminal operations to get an optional element.
Use case: Find the first active developer.

🔹 14. peek()
What it does: Debug intermediary steps (not recommended for production).
Use case: Log elements mid-pipeline.

🔹15. count()
What it does: Counts elements in the stream.
Use case: Count how many developers are assigned to a project.

✅ Practice Ideas
Use a single object model like:

Developer → with skills, salary, projects, orders

Project → with domain

Department → for grouping

You can practice all of the above with these relationships. Realistic and reusable!

Top comments (0)