个性化阅读
专注于IT技术分析

Scala Seq用法示例

本文概述

Seq是一个特征, 代表可以保证不变的索引序列。你可以使用元素索引来访问元素。它保持元素的插入顺序。

序列支持多种方法来查找元素或子序列的出现。它返回一个列表。


Scala Seq示例

在以下示例中, 我们将创建Seq并从Seq访问元素。

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        var seq:Seq[Int] = Seq(52, 85, 1, 8, 3, 2, 7)
        seq.foreach((element:Int) => print(element+" "))
        println("\nAccessing element by using index")
        println(seq(2))
    }
}

输出

52 85 1 8 3 2 7 
Accessing element by using index
1

你还可以通过使用反向方法以相反顺序访问元素。下面我们列出了一些常用的方法及其说明。


常用的Seq方法

Method Description
def contains [A1>:A](elem:A1):布尔值 检查给定元素是否按此顺序存在。
def copyToArray(xs:Array [A], start:Int, len:Int):单位 它将seq元素复制到数组。
def startsWith [B](that:GenSeq [B]):布尔值 它测试此序列是否以给定序列结尾。
def头:A 它选择此seq集合的第一个元素。
def indexOf(elem:A):整数 它找到此不变序列中值首次出现的索引。
def isEmpty:布尔值 它测试此序列是否为空。
def lastIndexOf(elem:A):Int 它查找此不可变序列中最后一次出现值的索引。
def反向:Seq [A] 它返回具有相反顺序元素的新序列。

Scala Seq示例

在此示例中, 我们应用了一些预定义的Seq特征方法。

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        var seq:Seq[Int] = Seq(52, 85, 1, 8, 3, 2, 7)
        seq.foreach((element:Int) => print(element+" "))
        println("\nis Empty: "+seq.isEmpty)
        println("Ends with (2, 7): "+ seq.endsWith(Seq(2, 7)))
        println("contains 8: "+ seq.contains(8))
        println("last index of 3 : "+seq.lastIndexOf(3))
        println("Reverse order of sequence: "+seq.reverse)
    }
}

输出

52 85 1 8 3 2 7 
is Empty: false
Ends with (2, 7): true
contains 8: true
last index of 3 : 4
Reverse order of sequence: List(7, 2, 3, 8, 1, 85, 52)
赞(0)
未经允许不得转载:srcmini » Scala Seq用法示例

评论 抢沙发

评论前必须登录!