0

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?

0

4 Answers 4

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

0

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

Comments

0

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

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.