Scala Vector用法示例

本文概述

  • Scala矢量示例
  • Scala矢量示例
向量是一种通用的, 不变的数据结构。它提供元素的随机访问。它适合大量元素的收集。
它扩展了抽象类AbstractSeq和IndexedSeq特质。
Scala矢量示例
import scala.collection.immutable._object MainObject{def main(args:Array[String]){var vector:Vector[Int] = Vector(5, 8, 3, 6, 9, 4) //Orvar vector2 = Vector(5, 2, 6, 3)var vector3 = Vector.emptyprintln(vector)println(vector2)println(vector3)}}

输出
Vector(5, 8, 3, 6, 9, 4)Vector(5, 2, 6, 3)Vector(

Scala矢量示例在下面的示例中, 我们创建了一个向量。你还可以添加新元素并合并两个向量。
import scala.collection.immutable._object MainObject{def main(args:Array[String]){var vector = Vector("Hocky", "Cricket", "Golf")var vector2 = Vector("Swimming")print("Vector Elements: ")vector.foreach((element:String) => print(element+" "))var newVector= vector :+ "Racing"// Adding a new element into vectorprint("\nVector Elements after adding: ")newVector.foreach((element:String) => print(element+" "))var mergeTwoVector = newVector ++ vector2// Merging two vectorprint("\nVector Elements after merging: ")mergeTwoVector.foreach((element:String) => print(element+" "))var reverse = mergeTwoVector.reverse// Reversing vector elementsprint("\nVector Elements after reversing: ")reverse.foreach((element:String) => print(element+" "))var sortedVector = mergeTwoVector.sorted// Sorting vector elementsprint("\nVector Elements after sorting: ")sortedVector.foreach((element:String) => print(element+" "))}}

【Scala Vector用法示例】输出
Vector Elements: Hocky Cricket Golf Vector Elements after adding: Hocky Cricket Golf Racing Vector Elements after merging: Hocky Cricket Golf Racing Swimming Vector Elements after reversing: Swimming Racing Golf Cricket Hocky Vector Elements after sorting: Cricket Golf Hocky Racing Swimming

    推荐阅读