A list is a collection which contains immutable data. List represents linked list in Scala. A List is immutable, if we need to create a list that is constantly changing, the preferred approach is to use a ListBuffer. The Scala List class holds a sequenced, linear list of items. A List can be built up efficiently only from back to front. the ListBuffer object is convenient when we want to build a list from front to back. It supports efficient prepend and append operations. Once we are done creating our list, call the toList method. To convert the ListBuffer into a List, Time taken will be constant. To use ListBuffer, scala.collection.mutable.ListBuffer class is imported, an instance of ListBuffer is created.
Example :
var name = new ListBuffer[datatype]() // empty buffer is created
var name = new ListBuffer("class", "gfg", "geeksforgeeks")
In the above example, first, an empty buffer is created here datatype indicates the type of data such as integer, string. Then created a buffer with three elements, of type string. Below operation can be performed on ListBuffer -
- By using L += e we can appends the element e in constant time.
- By using e +=: L we can prepends the element e in constant time.
- L.toList In constant time, It returns a list with the contents of the ListBuffer . We should not use the ListBuffer once changing it to a list.
Operations on ListBuffer
Creating instance of ListBuffer:
Scala
// Scala program to create a ListBuffer
// ListBuffer class is imported
import scala.collection.mutable.ListBuffer
// Creating object
object GfG
{
// Main Method
def main(args: Array[String])
{
// Instance of ListBuffer is created
var name = ListBuffer[String]()
name += "GeeksForGeeks"
name += "gfg"
name += "Class"
println(name)
}
}
Output:
ListBuffer(GeeksForGeeks, gfg, Class)
Access element from ListBuffer: Element is accessed same as list, ListBuffer(i) is used to accessed ith index element of list.
Scala
// Scala program to access element of ListBuffer
// ListBuffer class is imported
import scala.collection.mutable.ListBuffer
// Creating Object
object GFG
{
// Main Method
def main(args: Array[String])
{
// Instance of ListBuffer is created
var name = ListBuffer[String]()
name += "GeeksForGeeks"
name += "gfg"
name += "Class"
// Accessing 1th index element of listBuffer
println(name(1))
}
}
Output:
gfg
Adding elements in ListBuffer:
- Add single element to the buffer
ListBuffer+=( element)
- Add two or more elements (method has a varargs parameter)
ListBuffer+= (element1, element2, ..., elementN )
- Append one or more elements (uses a varargs parameter)
ListBuffer.append( elem1, elem2, ... elemN)
Scala
// Scala program to add element in ListBuffer
// ListBuffer class is imported
import scala.collection.mutable.ListBuffer
// Creating Object
object GFG
{
// Main Method
def main(args: Array[String])
{
// Instance of ListBuffer is created
var name = ListBuffer[String]()
// Adding one element
name += "GeeksForGeeks"
// Add two or more elements
name += ("gfg", "class")
// Adding one or more element using append method
name.append("Scala", "Article")
// Printing ListBuffer
println(name)
}
}
Output:
ListBuffer(GeeksForGeeks, gfg, class, Scala, Article)
Deleting ListBuffer Elements:
ListBuffer-= (element)
ListBuffer-= (elem1, elem2, ....., elemN)
Scala
// Scala program to delete element from ListBuffer
// ListBuffer class is imported
import scala.collection.mutable.ListBuffer
// Creating Object
object GFG
{
// Main Method
def main(args: Array[String])
{
// Instance of ListBuffer is created
var name = ListBuffer( "GeeksForGeeks", "gfg",
"class", "Scala",
"Article" )
// Deletes one element
name -= "GeeksForGeeks"
// Deletes two or more elements
name -= ("gfg", "class")
// Printing resultant ListBuffer
println(name)
}
}
Output:
ListBuffer(Scala, Article)
Deleting ListBuffer Elements using ListBuffer.remove() : The remove() method is used to delete one element by its position in the ListBuffer, or a series of elements beginning at a starting position.
Scala
// Scala program for remove method, on ListBuffer
// ListBuffer class is imported
import scala.collection.mutable.ListBuffer
// Creating Object
object GFG
{
// Main Method
def main(args: Array[String])
{
// Instance of ListBuffer is created
var name = ListBuffer( "GeeksForGeeks",
"gfg", "class",
"Scala", "Article" )
// Removing 0th index element
name.remove(0)
// Printing resultant ListBuffer
println(name)
name.remove(1, 3)
// Printing resultant ListBuffer
println(name)
}
}
Output:
ListBuffer(gfg, class, Scala, Article)
ListBuffer(gfg)
In Scala, a ListBuffer is a mutable sequence that represents a resizable array buffer. It allows elements to be added, removed, or updated at any position in constant time, making it useful for scenarios where frequent modifications to a list are required.
Here are some key features and operations of a ListBuffer in Scala:
A ListBuffer is created by invoking its constructor, which takes no arguments:
Scala
import scala.collection.mutable.ListBuffer
object ListBufferExample {
def main(args: Array[String]): Unit = {
val listBuffer = ListBuffer[Int]()
// Add elements to the list buffer
listBuffer += 1
listBuffer += 2
listBuffer += 3
// Append a sequence of elements to the list buffer
listBuffer ++= Seq(4, 5, 6)
// Insert an element at a specific index
listBuffer.insert(2, 10)
// Remove an element from the list buffer
listBuffer -= 3
// Update an element at a specific index
listBuffer.update(1, 20)
// Convert the list buffer to an immutable list
val list = listBuffer.toList
// Print the list buffer and the immutable list
println("List buffer: " + listBuffer)
println("List: " + list)
}
}
OutputList buffer: ListBuffer(1, 20, 10, 4, 5, 6)
List: List(1, 20, 10, 4, 5, 6)
In this example, we create a new ListBuffer and add, remove, and update elements in it. We then convert the ListBuffer to an immutable List and print both the ListBuffer and the List. As we can see from the output, the ListBuffer contains all the elements that were added to it, and the immutable List is a copy of the ListBuffer with the same elements in the same order.
Here are some advantages and disadvantages of using ListBuffer in Scala:
Advantages:
- Efficient additions, removals, and updates: ListBuffer provides efficient constant time additions, removals, and updates of elements, making it a good choice for
- scenarios where frequent modifications to a list are required.
- Flexibility: ListBuffer can be used in a variety of scenarios, including appending to the end of a list, inserting elements at a specific index, and removing elements from a list.
- Easy conversion to an immutable list: ListBuffer can be easily converted to an immutable List using the toList method.
Disadvantages:
- Mutable state: ListBuffer is a mutable data structure, meaning that its contents can be modified after creation. This can make it more difficult to reason about the behavior of a program and can lead to bugs.
- Not thread-safe: Because ListBuffer is mutable, it is not thread-safe by default. This means that multiple threads accessing the same ListBuffer can lead to race conditions and other concurrency-related issues.
- Overhead: Compared to immutable lists, ListBuffer has some overhead in terms of memory usage and performance. However, the overhead is generally small and is outweighed by the benefits of efficient modifications to the list.
Similar Reads
Overview
Basics
Control Statements
Scala | Decision Making (if, if-else, Nested if-else, if-else if)Decision making in programming is similar to decision making in real life. In decision making, a piece of code is executed when the given condition is fulfilled. Sometimes these are also termed as the Control flow statements. Scala uses control statements to control the flow of execution of the prog
5 min read
Scala | Loops(while, do..while, for, nested loops)Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Scala provides the different types of loop to handle the condition based situation in the progr
5 min read
Break statement in ScalaIn Scala, we use a break statement to break the execution of the loop in the program. Scala programming language does not contain any concept of break statement(in above 2.8 versions), instead of break statement, it provides a break method, which is used to break the execution of a program or a loop
3 min read
Scala | LiteralsAny constant value which can be assigned to the variable is called as literal/constant. The literals are a series of symbols utilized for describing a constant value in the code. There are many types of literals in Scala namely Character literals, String literals, Multi-Line String literals, Boolean
4 min read
OOP Concepts
Methods
Strings
Scala Packages
Scala Trait
Collections
Scala ListsA list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala. Lists represents
5 min read
Scala ListBufferA list is a collection which contains immutable data. List represents linked list in Scala. A List is immutable, if we need to create a list that is constantly changing, the preferred approach is to use a ListBuffer. The Scala List class holds a sequenced, linear list of items. A List can be built u
6 min read
ListSet in ScalaA set is a collection which only contains unique items which are not repeatable and a list is a collection which contains immutable data. In scala, ListSet class implements immutable sets using a list-based data structure. Elements are stored in reversed insertion order, That means the newest elemen
6 min read
Scala MapMap is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. Key-value pairs can have any data type. However, data type once used for any key and value must be consistent throughout. Maps are classified into two types: m
5 min read
Scala | ArraysArray is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values. It corresponds to arr
6 min read
Scala | ArrayBufferArray in scala is homogeneous and mutable, i.e it contains elements of the same data type and its elements can change but the size of array size canât change. To create a mutable, indexed sequence whose size can change ArrayBuffer class is used. To use, ArrayBuffer, scala.collection.mutable.ArrayBuf
4 min read
Scala | TupleTuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable. An example of a tuple storing an integer, a string, and boolean value. val name = (15, "Chandan", tr
5 min read
Set in Scala | Set-1A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request. Syntax: // Immutable set val variable_name: Set[type] = Set(item1, item2, ite
3 min read
Set in Scala | Set-2Prerequisite: Set in Scala | Set-1Adding items in Mutable SetIn Set, We can only add new elements in mutable set. +=, ++== and add() method is used to add new elements when we are working with mutable set in mutable collection and += is used to add new elements when we are working with mutable set i
7 min read
BitSet in ScalaA set is a collection which only contains unique items which are not repeatable. A BitSet is a collection of small integers as the bits of a larger integer. Non negative integers sets which represented as array of variable-size of bits packed into 64-bit words is called BitSets. The largest number s
5 min read
HashSet In ScalaHashSet is sealed class. It extends immutable Set and AbstractSet trait. Hash code is used to store elements. It neither sorts the elements nor maintains insertion order . The Set interface implemented by the HashSet class, backed by a hash table . In Scala, A concrete implementation of Set semantic
4 min read
Stack in ScalaA stack is a data structure that follows the last-in, first-out(LIFO) principle. We can add or remove element only from one end called top. Scala has both mutable and immutable versions of a stack. Syntax : import scala.collection.mutable.Stack var s = Stack[type]() // OR var s = Stack(val1, val2, v
3 min read
HashMap in ScalaHashMap is a part of Scala Collection's. It is used to store element and return a map. A HashMap is a combination of key and value pairs which are stored using a Hash Table data structure. It provides the basic implementation of Map. Syntax: var hashMapName = HashMap("key1"->"value1", "key2"->"value
3 min read
TreeSet in ScalaSet is a data structure which allows us to store elements which are unique. The ordering of elements does not guarantee by the Set, than a TreeSet will make elements in a given order. In Scala, TreeSet have two versions: scala.collection.immutable.TreeSet and scala.collection.mutable.TreeSet. Syntax
4 min read
Iterators in ScalaAn iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. An iterator defined for any collection does not load the entire collection into the memory but loads elements one after the other. Ther
5 min read
Scala | OptionThe Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null. Important points : The insta
3 min read