Scala program to merge two vectors using the ++ operator

Here, we are going to learn how to merge two vectors using the ++ operator in Scala programming language?
Submitted by Nidhi, on June 12, 2021 [Last updated : March 11, 2023]

Scala - Merge Two Vectors (Using ++ Operator)

Here, we will create two objects of Vector collection. Then we will merge two vectors using the "++" operator. After that, we will print the result on the console screen.

The Vector is an immutable data structure. We can access vector elements randomly. It extends an abstract class AbstractSeq and IndexedSeq trait. We use the Vector collection to store a large number of elements.

Scala code to merge two vectors using the ++ operator

The source code to merge two vectors using the "++" operator is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to merge two vectors

import scala.collection.immutable._

object Sample {
  // Main method
  def main(args: Array[String]) {
    var vector1 = Vector(10, 20, 30);
    var vector2 = Vector(40, 50);

    var vectorNew = vector1 ++ vector2;
    println(vectorNew);
  }
}

Output

Vector(10, 20, 30, 40, 50)

Explanation

Here, we used an object-oriented approach to create the program. And, we imported Collection classes using the below statement,

import scala.collection.immutable._

And, we also created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.

In the main() function, we created two vectors vector1, vector2 using Vector collection. Then we merged both vectors using the "++" operator and assigned the result into vectorNew. After that, we printed the elements of vectorNew on the console screen.

Scala Vector Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.