ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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,

  • ++ operator
  • ::: operator

Both are used to add a list to a list. 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.

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 :::.

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)
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.