MovieIterator class implementation
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2021-12-13
Problem Statement
Design a MovieIterator class that allows traversing a collection of movies in a structured and flexible way. The iterator should support sequential access, filtering, and optional operations like skipping or resetting.
Functional Requirements (FR)
Iteration
•Traverse a collection of movies sequentially.
•Provide methods to check for more elements and retrieve the next movie.
Filtering (Optional)
•Support filtering movies by attributes (genre, release year, rating, etc.) during iteration.
State Management
•Maintain the current position in the collection.
•Support resetting the iterator to the beginning.
Concurrency (Optional)
•Handle cases where the underlying collection is modified during iteration.
Suggested Methods
1.hasNext(): boolean
•Returns true if there are more movies to iterate over.
2.next(): Movie
•Returns the next movie in the collection.
3.reset(): void
•Resets the iterator to the start of the collection.
4.filter(predicate: Movie -> boolean): void (Optional)
•Filters the movies based on a predicate function.
Suggested Class Design
Class: Movie
•Attributes: title, genre, releaseYear, rating
Class: MovieCollection
•Attributes: movies → List of Movie objects
•Methods:
•getIterator(): MovieIterator → returns an iterator for the collection
Class: MovieIterator
•Attributes:
•movies → reference to the collection
•currentIndex → position in the collection
•filterPredicate → optional predicate for filtering
•Methods:
•hasNext() → checks if more movies are available
•next() → returns the next movie satisfying the filter
•reset() → resets iterator to start
•filter(predicate) → sets the filter condition
Data Flow (High-Level)
1.Client creates a MovieCollection → adds movies.
2.Client calls getIterator() → obtains a MovieIterator.
3.Client calls hasNext() and next() in a loop → iterates over movies.
4.Optional: Client applies filter() → iterator returns only movies matching the filter.
5.Client can call reset() → start iteration from the beginning.
Key Design Considerations
•Encapsulation: Iterator should not expose internal collection details.
•Lazy Evaluation: Filtering should be applied dynamically during iteration.
•Efficiency: Avoid copying the entire collection for filtering.
•Thread Safety (Optional): Handle concurrent modifications if needed.
•Extensibility: Support additional operations like skip(n) or peek