
- Scala Collections Tutorial
- Scala Collections - Home
- Scala Collections - Overview
- Scala Collections - Environment Setup
- Scala Collections - Arrays
- Scala Collections - Array
- Scala Collections - Multi-Dimensional Array
- Scala Collections - Array using Range
- Scala Collections - ArrayBuffer
- Scala Collections - Lists
- Scala Collections - List
- Scala Collections - ListBuffer
- Scala Collections - ListSet
- Scala Collections - Vector
- Scala Collections - Sets
- Scala Collections - Set
- Scala Collections - BitSet
- Scala Collections - HashSet
- Scala Collections - TreeSet
- Scala Collections - Maps
- Scala Collections - Map
- Scala Collections - HashMap
- Scala Collections - ListMap
- Scala Collections - Miscellaneous
- Scala Collections - Iterator
- Scala Collections - Option
- Scala Collections - Queue
- Scala Collections - Tuple
- Scala Collections - Seq
- Scala Collections - Stack
- Scala Collections - Stream
- Scala Collections Combinator methods
- Scala Collections - drop
- Scala Collections - dropWhile
- Scala Collections - filter
- Scala Collections - find
- Scala Collections - flatMap
- Scala Collections - flatten
- Scala Collections - fold
- Scala Collections - foldLeft
- Scala Collections - foldRight
- Scala Collections - map
- Scala Collections - partition
- Scala Collections - reduce
- Scala Collections - scan
- Scala Collections - zip
- Scala Collections Useful Resources
- Scala Collections - Quick Guide
- Scala Collections - Useful Resources
- Scala Collections - Discussion
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