Balaji Krishnamoorthy
Balaji Krishnamoorthy

Reputation: 11

Scala - create a new list and update particular element from existing list

I am new to Scala and new OOP too. How can I update a particular element in a list while creating a new list.

val numbers= List(1,2,3,4,5)
val result = numbers.map(_*2) 

I need to update third element only -> multiply by 2. How can I do that by using map?

Upvotes: 0

Views: 281

Answers (4)

swapnil shashank
swapnil shashank

Reputation: 997

1st and the foremost scala is FOP and not OOP. You can update any element of a list through the keyword "updated", see the following example for details:

Signature :- updated(index,value)

val numbers= List(1,2,3,4,5)
print(numbers.updated(2,10))

Now here the 1st argument is the index and the 2nd argument is the value. The result of this code will modify the list to: List(1, 2, 10, 4, 5).

Upvotes: 0

Berthur
Berthur

Reputation: 4495

I think the clearest way of achieving this is by using updated(index: Int, elem: Int). For your example, it could be applied as follows:

val result = numbers.updated(2, numbers(2) * 2)

Upvotes: 2

Dima
Dima

Reputation: 40508

list.zipWithIndex creates a list of pairs with original element on the left, and index in the list on the right (indices are 0-based, so "third element" is at index 2).

val result = number.zipWithIndex.map { 
   case (n, 2) => n*2
   case n => n
}

This creates an intermediate list holding the pairs, and then maps through it to do your transformation. A bit more efficient approach is to use iterator. Iterators a 'lazy', so, rather than creating an intermediate container, it will generate the pairs one-by-one, and send them straight to the .map:

val result = number.iterator.zipWithIndex.map {
  case (n, 2) => n*2
  case n => n
}.toList

Upvotes: 0

Tzach Zohar
Tzach Zohar

Reputation: 37852

You can use zipWithIndex to map the list into a list of tuples, where each element is accompanied by its index. Then, using map with pattern matching - you single out the third element (index = 2):

val numbers = List(1,2,3,4,5)
val result = numbers.zipWithIndex.map {
  case (v, i) if i == 2 => v * 2
  case (v, _) => v
}
// result: List[Int] = List(1, 2, 6, 4, 5)

Alternatively - you can use patch, which replaces a sub-sequence with a provided one:

numbers.patch(from = 2, patch = Seq(numbers(2) * 2), replaced = 1)

Upvotes: 2

Related Questions