我正在从某些函数中接收向量列表,例如
(List(Vector(1), Vector(1, 2), Vector(1, 3), Vector(1, 2, 4), Vector(1, 5)))
我想将其转换为
等整数的不同值List(1,2,3,4,5)
在Scala中使用完整的不变性。
请建议实现它的有效方法。
您可以在List
上使用flatten
和distinct
方法。
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)