Manvi - 1 year ago 77

Scala Question

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 Source

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)
```