使用“下一个”和“上一个”值映射的Scala列表

时间:2016-09-12 11:04:57

标签: performance scala functional-programming

改造的最佳方式是什么:

val arr: List[String]

致:

val mapArr: List[Tuple[Int, String]] 

其中:

each Tuple is:
  - String value is the an odd index element of the list
  - Int the size of the previous value. 

示例:

val stringArr = List("a", "aaa", "bb", "abc")
val resultShouldBe = List((1, "aaa"), (2, "abc"))  

1 个答案:

答案 0 :(得分:5)

您可以使用IterableLike.grouped

val result = stringArr
               .grouped(2)
               .collect { case List(toIndex, value) => (toIndex.length, value) }
               .toList

哪个收益率:

scala> val stringArr = List("a", "aaa", "bb", "abc")
stringArr: List[String] = List(a, aaa, bb, abc)

scala> stringArr.grouped(2).collect { case List(toIndex, value) => (toIndex.length, value) }.toList
res1: List[(Int, String)] = List((1,aaa), (2,abc))