0

val arr = List(8, 15, 22, 1, 10, 6, 18, 18, 1) arr.zipWithIndex.map(_._2) works and give me index of the elements in the list .How to access the index and the element as part of the map function

1
  • Your map function already has the value and the index, but you are discarding the value. So it is not clear to me what is the question. Commented May 19, 2020 at 12:53

3 Answers 3

1
val arr = List(8, 15, 22, 1, 10, 6, 18, 18, 1)
arr.zipWithIndex.map(zippedList => (zippedList._1, zippedList._2))

if you want to access the element it's ._1 and index ._2

you can also use this:

arr.zipWithIndex.map {
    case (x, y) => print(x, y)
  }

and so the operation on x and y what ever you want to do.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Raman. I was trying to destruct the inside the parameter list itsef.
1

This is typically done using zipWithIndex and pattern matching:

arr.zipWithIndex.map{ case (value, index) => ??? }

Comments

0

You can use partial function to deconstruct a tuple

val arr = List(8, 15, 22, 1, 10, 6, 18, 18, 1)
arr.zipWithIndex.map { case (value, index) => println(value -> index) }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.