Streams in Java

Core Concepts You Must Understand {#core-concepts}

Stream Pipeline Structure

Collection.stream()
    .intermediateOperation1()
    .intermediateOperation2()
    .terminalOperation();

Key Principles:

  1. Streams are lazy - Operations are only executed when a terminal operation is called

  2. Streams are consumed - Can only be used once

  3. Streams don't modify original data - They create new streams

  4. Operations can be chained - Fluent API design

Essential Operations {#essential-operations}

Intermediate Operations (Return Stream)

1. filter() - Keep Elements That Match Condition

// Keep even numbers
numbers.stream()
    .filter(n -> n % 2 == 0)

// Keep employees with high salary
employees.stream()
    .filter(emp -> emp.getSalary() > 75000)

2. map() - Transform Each Element

3. flatMap() - Flatten Nested Structures

4. distinct() - Remove Duplicates

5. sorted() - Sort Elements

6. limit() and skip()

Terminal Operations (Return Result)

1. collect() - Most Important Terminal Operation

2. reduce() - Combine All Elements

3. forEach() - Perform Action on Each Element

4. count() - Count Elements

5. Finding Operations

6. Matching Operations

7. Min/Max Operations

Advanced Patterns and Collectors {#advanced-patterns}

1. Grouping Operations

Basic Grouping

Advanced Grouping

Multi-level Grouping

2. Partitioning

3. String Operations

4. Statistical Operations

Common Interview Questions with Solutions {#interview-questions}

Question 1: Employee Filtering and Sorting

"Find all employees with salary > 50k, sort by name, return as list"

Question 2: Department Analysis

"Group employees by department and count how many in each department"

Question 3: Top N Elements

"Get the top 3 highest paid employees"

Question 4: Collection Transformation

"Convert list of employees to a map where key is employee ID and value is employee name"

Question 5: Complex Filtering

"Find employees from IT department with salary > 60k and age < 35"

Question 6: String Manipulation

"Get all unique first names from employees, convert to uppercase, sort alphabetically"

Question 7: Nested Data Processing

"Get all unique skills from all employees"

Question 8: Statistical Analysis

"Find the average salary of employees in each department"

Question 9: Conditional Operations

"Check if any employee in HR department earns more than 80k"

Question 10: Complex Aggregation

"Get the name of the highest paid employee in each department"

Working with Numbers Streams {#numbers-streams}

IntStream, LongStream, DoubleStream

Best Practices for Interviews {#best-practices}

1. Always Chain Operations Fluently

2. Handle Optional Results Properly

3. Use Method References When Possible

4. Choose Right Collection Type

5. Remember Proper Import Statements

Common Mistakes to Avoid {#mistakes-to-avoid}

1. Wrong Lambda Syntax in reduce()

2. Forgetting Terminal Operation

3. Reusing Streams

4. Not Handling Empty Collections

5. Confusing map() vs flatMap()

Practice Problems {#practice-problems}

Beginner Level

Problem 1: Basic Filtering

Problem 2: String Transformation

Intermediate Level

Problem 3: Grouping and Counting

Problem 4: Complex Filtering

Advanced Level

Problem 5: Multi-level Grouping

Problem 6: Custom Collector

Parallel Streams (Bonus Topic)

When to Use Parallel Streams

Cautions with Parallel Streams

  • Not always faster (overhead for small datasets)

  • Thread-safety concerns

  • Order may not be preserved

  • Avoid for I/O operations

Advanced Collectors (Expert Level)

Custom Collectors

Performance Tips

1. Use Primitive Streams When Possible

2. Filter Early

3. Use Limit When Appropriate

Final Checklist for Interviews {#final-checklist}

Must-Know Operations

  • [ ] filter() - Keep elements matching condition

  • [ ] map() - Transform each element

  • [ ] collect() - Convert to collection (with Collectors.toList(), toSet(), toMap())

  • [ ] reduce() - Combine elements (remember: needs 2 parameters)

  • [ ] sorted() - Sort elements (with Comparator.comparing())

  • [ ] groupingBy() - Group elements by key

  • [ ] flatMap() - Flatten nested structures

Must-Know Patterns

  • [ ] Filter → Map → Collect

  • [ ] GroupBy with counting/averaging

  • [ ] Finding max/min elements

  • [ ] Handling Optional results

  • [ ] Method references vs lambda expressions

Must-Avoid Mistakes

  • [ ] Wrong reduce() syntax

  • [ ] Forgetting terminal operations

  • [ ] Reusing streams

  • [ ] Not handling Optional results

  • [ ] Missing imports

Interview Confidence Boosters

  • [ ] Practice chaining operations fluently

  • [ ] Know when to use parallel streams

  • [ ] Understand lazy evaluation

  • [ ] Can explain benefits over traditional loops

  • [ ] Comfortable with complex grouping operations

Conclusion

Mastering Java Streams is crucial for modern Java interviews. The key is to:

  1. Understand the concepts - Know the difference between intermediate and terminal operations

  2. Practice the patterns - Filter-Map-Collect is the most common

  3. Handle edge cases - Always deal with Optional results properly

  4. Write clean code - Use method references and chain operations fluently

  5. Know the common mistakes - Avoid them during your interview

Last updated