11.9. Deleting Array and ArrayBuffer Elements

Problem

You want to delete elements from an Array or ArrayBuffer.

Solution

An ArrayBuffer is a mutable sequence, so you can delete elements with the usual -=, --=, remove, and clear methods.

You can remove one or more elements with -=:

import scala.collection.mutable.ArrayBuffer
val x = ArrayBuffer('a', 'b', 'c', 'd', 'e')

// remove one element
x -= 'a'

// remove multiple elements (methods defines a varargs param)
x -= ('b', 'c')

Use --= to remove multiple elements that are declared in another collection (any collection that extends TraversableOnce):

val x = ArrayBuffer('a', 'b', 'c', 'd', 'e')
x --= Seq('a', 'b')
x --= Array('c')
x --= Set('d')

Use the remove method to delete one element by its position in the ArrayBuffer, or a series of elements beginning at a starting position:

scala> val x = ArrayBuffer('a', 'b', 'c', 'd', 'e', 'f')
x: scala.collection.mutable.ArrayBuffer[Char] = ArrayBuffer(a, b, c, d, e, f)

scala> x.remove(0)
res0: Char = a

scala> x
res1: scala.collection.mutable.ArrayBuffer[Char] = ArrayBuffer(b, c, d, e, f)

scala> x.remove(1, 3)

scala> x
res2: scala.collection.mutable.ArrayBuffer[Char] = ArrayBuffer(b, f)

In these examples, the collection that contains the elements to be removed can be any collection that extends TraversableOnce, so removeThese can be a Seq, Array, Vector, and many other types that extend TraversableOnce.

The clear method removes all the elements from an ArrayBuffer:

scala> var a = ArrayBuffer(1,2,3,4,5) ...

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.