Scala:以不可变的方式列表到唯一项目列表的列表



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

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

最新更新