refactored flatMap