boredmgr
boredmgr

Reputation: 261

access index and value of a scala list inside a map function

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

Upvotes: 0

Views: 367

Answers (3)

Ivan Stanislavciuc
Ivan Stanislavciuc

Reputation: 7275

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

Upvotes: 0

Tim
Tim

Reputation: 27356

This is typically done using zipWithIndex and pattern matching:

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

Upvotes: 1

Raman Mishra
Raman Mishra

Reputation: 2686

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.

Upvotes: 1

Related Questions