Scala:向量列表以不可变的方式指向唯一的项目列表

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

我正在从某些函数接收向量列表,例如

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

我想将它转换成不同的整数值,例如

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

在 Scala 中使用完全不变性。

请建议实现它的有效方法是什么。

您可以在 List 上使用 flattendistinct 方法。

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)

这是替代解决方案。

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

lst.flatten.toSet.toList

List[Int] = List(5, 1, 2, 3, 4)