11.4. Deleting Elements from a List (or ListBuffer)

Problem

You want to delete elements from a List or ListBuffer.

Solution

A List is immutable, so you can’t delete elements from it, but you can filter out the elements you don’t want while you assign the result to a new variable:

scala> val originalList = List(5, 1, 4, 3, 2)
originalList: List[Int] = List(5, 1, 4, 3, 2)

scala> val newList = originalList.filter(_ > 2)
newList: List[Int] = List(5, 4, 3)

Rather than continually assigning the result of operations like this to a new variable, you can declare your variable as a var and reassign the result of the operation back to itself:

scala> var x = List(5, 1, 4, 3, 2)
x: List[Int] = List(5, 1, 4, 3, 2)

scala> x = x.filter(_ > 2)
x: List[Int] = List(5, 4, 3)

See Chapter 10 for other ways to get subsets of a collection using methods like filter, partition, splitAt, take, and more.

ListBuffer

If you’re going to be modifying a list frequently, it may be better to use a ListBuffer instead of a List. A ListBuffer is mutable, so you can remove items from it using all the methods for mutable sequences shown in Chapter 10. For example, assuming you’ve created a ListBuffer like this:

import scala.collection.mutable.ListBuffer
val x = ListBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9)

You can delete one element at a time, by value:

scala> x -= 5
res0: x.type = ListBuffer(1, 2, 3, 4, 6, 7, 8, 9)

You can delete two or more elements at once:

scala> x -= (2, 3)
res1: x.type = ListBuffer(1, 4, 6, 7, 8, 9)

(That method looks ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.