Manvi Manvi - 12 days ago 5
Scala Question

Scala: List of vectors to Unique List of items in immutable way

I am receiving list of vectors from some function like

(List(Vector(1), Vector(1, 2), Vector(1, 3), Vector(1, 2, 4), Vector(1, 5)))


I want to convert it into distinct values of integers like

List(1,2,3,4,5)


in Scala using complete immutability.

Please suggest what are the efficient ways to achieve it.

Answer

You can use the flatten and distinct methods on List.

val list = List(Vector(1), 
                Vector(1, 2), 
                Vector(1, 3), 
                Vector(1, 2, 4), 
                Vector(1, 5))

val flattened = list.flatten // Gives List(1, 1, 2, 1, 3, 1, 2, 4, 1, 5)

val distinct = flattened.distinct // Gives List(1, 2, 3, 4, 5)