Scala How to remove item from list

In our previous tutorial, we have covered how to create a list and add an element to a list. In this tutorial, we shall see how to remove an item from a list.

There are multiple ways to remove or delete an element from a list in Scala.

1) As discussed in our previous tutorial, that List in Scala is immutable. So you can’t literally remove an element from a list, but can create a new list by removing the desired element from the list.

scala> val a = List(1,2,3,4,5)

a: List[Int] = List(1, 2, 3, 4, 5)

scala> val b = a.filter(_ != 3)

b: List[Int] = List(1, 2, 4, 5)

Removal of list elements

2) Let’s work on ListBuffer data structure. Since ListBuffer is a mutable data structure, we can remove an element from the list.

scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer


scala> val a = ListBuffer(1,2,3,4,5)
a: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 5)

scala> a -= 1
res0: a.type = ListBuffer(2, 3, 4, 5)

scala> a -= 2
res1: a.type = ListBuffer(3, 4, 5)

scala> a -= 5
res2: a.type = ListBuffer(3, 4)

In the first statement, we have imported the ListBuffer class. If you are using an IDE it will take care of the import. If you are using Scala RELP you have to know the exact package where ListBuffer class is available to import. Next, we have initialized a ListBuffer of integer type containing 1 to 5 number. In the next three statements we have removed 1,2,5 elements subsequently.

Removal of list elements

3) So the third way is to remove item based on index position.

import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> val a = ListBuffer(1,2,3,4,5)
a: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 5)

scala> a.remove(0)
res0: Int = 1

scala> print(a)
ListBuffer(2, 3, 4, 5)

After initializing the ListBuffer with 1 to 5 numbers, we have used remove function with 0 as parameter which is our desired index (starting from 0) that needs to be removed. You can see in the next print statement where it removes the number 1 which is present in the index 0.

scala> a.remove(3)
res2: Int = 5

scala> print(a)
ListBuffer(2, 3, 4)

Next we have removed the number present in the index (starting from 0) 3 which is number 5.

Removal of list elements

Feel free to comment for questions and clarifications.

© 2022, Datalieve . All rights reserved.

Leave a Reply

Your email address will not be published. Required fields are marked *

You cannot copy content of this page