1

What would be the best way to transform:

val arr: List[String]

To:

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

Where:

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

Example:

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

1 Answer 1

5

You can use IterableLike.grouped for that:

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

Which yields:

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))
8
  • thanks @yuval However, The current implementation produce a bug if the list is not even. If the list is odd we should basically skip the last element.
    – ypriverol
    Commented Sep 12, 2016 at 12:25
  • @ypriverol But if the list is odd, what do you pair the last element with? Commented Sep 12, 2016 at 12:58
  • I modified your solution to remove the last element if is an even list: val result = if(stringArr.length % 2 != 0) stringArr.dropRight(1).grouped(2).map { case List(toIndex, value) => (value, toIndex.length)}.toList else stringArr.grouped(2).map { case List(toIndex, value) => (value, toIndex.length)}.toList
    – ypriverol
    Commented Sep 12, 2016 at 13:10
  • Why do you need to dropRight? collect will skip any single element List. Commented Sep 12, 2016 at 13:13
  • 1
    @ypriverol Are you sure you're using collect and not map? Look at my answer, I've modified it an hour ago. Commented Sep 12, 2016 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.