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)