Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a given item in a list?

Tags:

list

scala

This describes the problem pretty well:

scala> var l2 = List(1,2,3)
l2: List[Int] = List(1, 2, 3)

scala> l2(2) = 55
<console>:10: error: value update is not a member of List[Int]
              l2(2) = 55
              ^
like image 429
Ska Avatar asked Feb 23 '11 17:02

Ska


People also ask

Can you replace an element in a list?

The easiest way to replace an item in a list is to use the Python indexing syntax . Indexing allows you to choose an element or range of elements in a list. With the assignment operator, you can change a value at a given position in a list.

How do you replace an item in a list with a string?

Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .


1 Answers

scala.List is immutable, meaning you cannot update it in place. If you want to create a copy of your List which contains the updated mapping, you can do the following:

val updated = l2.updated( 2, 55 )

There are mutable ordered sequence types as well, in scala.collection.mutable, such as Buffer types which seem more like what you want. If you try the following you should have more success:

scala> import scala.collection._
import scala.collection._
scala> val b = mutable.Buffer(1,2,3)
b: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3)
scala> b(2) = 55
scala> b
res1: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 55)

Edit: Just to note that some other answers have mentioned that you should use a "mutable List type" - this is true, but "List" in Scala just refers to the single-linked list, whereas in Java it's generally used for any ordered, random-access collection. There is also a DoubleLinkedList, which is more like a Java LinkedList, and a MutableList, which is a type used for the internals of some other types.

Generally speaking what you probably want in Scala is a Buffer for this job; especially since the default implementation is an ArrayBuffer, which is pretty close to being the same as ArrayList, most peoples' default, in Java.

If you ever want to find out what the closest "mapping" of a Java collections interface to the Scala world is, though, the easiest thing to do is probably just check what JavaConversions does. In this case you can see the mapping is to Buffer:

scala.collection.mutable.Buffer <=> java.util.List
like image 134
Calum Avatar answered Oct 21 '22 18:10

Calum