Home »
Scala
Scala List Concatenation: ++ vs ::: operators, which is better?
Scala List Concatenation: ++ vs ::: – Here, we will learn about operators used for list concatenation. Different operators used to perform the operation and which is better?
Submitted by Shivang Yadav, on December 28, 2020
List in Scala is a collection which is used to store data in the form of linked-list.
Example:
List(2, "Scala programming Language" , 2008)
List concatenation in Scala
It is adding a list at the end of list. It is one of the methods to add elements to a list.
Two methods to concatenate lists in Scala,
Both are used to add a list to a list.
Example of list concatenation
Here, is a program to illustrate the working of both:
object myObject {
def main(args:Array[String]) {
val list1 = List("C++", "java", "Python")
val list2 = List("Scala", "C#")
println("List concatenated using ++ operator : " + ( list1 ++ list2 ) )
println("List concatenated using ::: operator : " + ( list1 ::: list2 ) )
}
}
Output:
List concatenated using ++ operator : List(C++, java, Python, Scala, C#)
List concatenated using ::: operator : List(C++, java, Python, Scala, C#)
The output of both the operators is the same but the computation time and some other factors are different.
Which one is better for list concatenating: ++ or :::
In terms of computation time, the ::: operator is faster, being right associative as compared to ++ operator. But when it comes to versatility ++ operator is far more better as it can be used to concatenate any two collections which is not possible with :::.
Example
Program to illustrate adding of concatenating two different collection (list with another collection, resulting in to list)
object myObject {
def main(args:Array[String]) {
val list1 = List("C++", "java", "Python")
val string1 = "Scala"
println("List concatenating string at the end of list using ++ operator : " + ( list1 ++ string1 ) )
}
}
Output:
List concatenating string at the end of list using ++ operator : List(C++, java, Python, S, c, a, l, a)