Scala Collections - ListBuffer



Scala provides a data structure, the ListBuffer, which is more efficient than List while adding/removing elements in a list. It provides methods to prepend, append elements to a list.

Declaring ListBuffer Variables

The following is the syntax for declaring an ListBuffer variable.

Syntax

var z = ListBuffer[String]()

Here, z is declared as an list-buffer of Strings which is initially empty. Values can be added by using commands like the following −

Command

z += "Zara";
z += "Nuha";
z += "Ayan";

Processing ListBuffer

Below is an example program of showing how to create, initialize and process ListBuffer −

Example

import scala.collection.mutable.ListBuffer 
object Demo {
   def main(args: Array[String]) = {
      var myList = ListBuffer("Zara","Nuha","Ayan")
      println(myList);
      // Add an element
      myList += "Welcome";
      // Add two element
      myList += ("To", "Tutorialspoint");
      println(myList);
      // Remove an element
      myList -= "Welcome";
      // print second element
      println(myList(1));
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

ListBuffer(Zara, Nuha, Ayan)
ListBuffer(Zara, Nuha, Ayan, Welcome, To, Tutorialspoint)
Nuha
Advertisements