enhancement
With $list.map(x -> ...) you can transform a list by applying a function x -> ... to each element. If the inner function itself returns a list, then you get a list of lists. Sometimes this may be desirable, but sometimes not. If you want to transform a list in such a way that each element possibly becomes several (or no) elements, then you have to smooth the result again afterwards with .flatten().
Instead, you should be able to perform the transformation directly with $list.flatMap(x -> ...). This is easier to understand and at the same time more efficient, because one result list is built directly instead of many.