scala list,scala迭代器_Scala選項和迭代器示例

 2023-11-19 阅读 27 评论 0

摘要:scala迭代器Scala Option can be defined as container that holds zero or more elements of the given type. The option[T] can return Some[T] or None object which represents a missing value. Scala選項可以定義為包含零個或多個給定類型元素的容器。 option[T]可以返

scala迭代器

Scala Option can be defined as container that holds zero or more elements of the given type. The option[T] can return Some[T] or None object which represents a missing value.

Scala選項可以定義為包含零個或多個給定類型元素的容器。 option[T]可以返回表示缺少值的Some[T]None對象。

Consider an example of how to create a option;

考慮一個如何創建一個選項的例子。

val msg : Option[String] = Some("Option is a Scala collection")

scala list,Consider an example of how to assign a none value;

考慮一個如何分配無值的例子。

val msg : Option[String] = None

Create Student.scala class in Scala IDE as;

在Scala IDE中將Student.scala類創建為;

case class Student(id: Int,Name: String,marks: Float,gender: Option[String])object TestStudent {private val students = Map(1 -> Student(10, "John", 62.5f, Some("male")),2 -> Student(12, "Adam", 70.5f, Some("female")))def findById(id: Int): Option[Student] = students.get(id)def findAll = students.values
}

Here we are defining a class student with id, name, marks and gender as attributes. Create an object TestStudent in which we define findById method that returns an Option of type Student and findAll which retrieves the values from students map.

在這里,我們定義了一個以id,姓名,標記和性別為屬性的班級學生。 創建一個對象TestStudent在其中定義findById方法,該方法返回Student類型的Option,而findAll從學生映射中檢索值。

scala array。Now create another object s1.scala as
S1.scala

現在創建另一個對象s1.scala作為
S1.scala

object S1 {def main(args: Array[String]) {val st1 = TestStudent.findById(2)if (st1.isDefined) {println(st1.get.id)println(st1.get.Name)println(st1.get.marks)}}}

Below image shows the output produced when we run S1 as scala application.

下圖顯示了將S1作為scala應用程序運行時產生的輸出。

Let’s look at some other examples for Scala Option.

讓我們看看Scala Option的其他示例。

指定默認值 (Specifying default value)

iterator迭代器詳解、The default value can be specified using getOrElse method.

可以使用getOrElse方法指定默認值。

For example create a scala object as below:
GetorElse.scala

例如,創建一個scala對象,如下所示:
GetorElse.scala

object GetorElse {def main(args: Array[String]) {val stud = Student(14, "Chris", 45f, None)println(stud.gender.getOrElse("Gender not specified"))}}

Below image shows the output produced as default value since gender was missing.

下圖顯示了由于缺少性別而產生的默認值輸出。

迭代器python、The gender is specified as None while creating stud instance and hence the message “Gender not specified” is printed.

創建螺柱實例時將性別指定為“無”,因此將顯示消息“未指定性別”。

模式匹配 (Pattern Matching)

The optional values can be taken apart through pattern matching.

可選值可以通過模式匹配分開。

For instance:

例如:

Scala獲取列表中的前5個元素,KeyPatternMatch.scala

KeyPatternMatch.scala

object KeyPatternMatch {def main(args: Array[String]) {val student = Map(12 -> "Anderson", 14 -> "Reena")println("Student Name with id 12  : " + displaykey(student.get(12)))println("Student Name with id 14 : " + displaykey(student.get(14)))}def displaykey(a: Option[String]) = a match {case Some(t) => tcase None    => "?"}
}

Output:

輸出:

Student Name with id 12  : Anderson
Student Name with id 14 : Reena

isEmpty() method

isEmpty()方法

scala高階函數?The isEmpty() method is used to check whether the option returns empty or not.

isEmpty()方法用于檢查選項是否返回空。

For example;
Empty.scala

例如;
Empty.scala

object Empty {def main(args: Array[String]) {val x: Option[Int] = Some(5)val y: Option[Int] = Noneprintln("Check X is Empty: " + x.isEmpty)println("Check Y is Empty: " + y.isEmpty)}
}

It produces below output.

它產生以下輸出。

Check X is Empty: false
Check Y is Empty: true

有用的期權方法 (Useful Option Methods)

scala樣例類,def isDefined: Boolean → Returns true if the option is an instance of Some, else returns false

def isDefined:布爾值 →如果選項是Some的實例,則返回true,否則返回false

def or Null → Returns the option’s value if it is nonempty, or null if it is empty.

def或Null →如果選項為非空,則返回其值;如果為空,則返回null。

def isEmpty: Boolean → Returns true if the option is None, false otherwise.

def isEmpty:布爾值 →如果選項為None,則返回true,否則返回false。

scala option,def get: X → Returns the option’s value.

def get:X →返回選項的值。

def foreach[Y](f: (Z) => Y): Unit → Apply the given procedure f to the option’s value, if it is nonempty.

def foreach [Y](f:(Z)=> Y):單位 →如果給定過程f為非空值,則將其應用于該選項的值。

Scala迭代器 (Scala Iterators)

An Iterator allows user to iterate over the collection thereby accessing all the elements. The core operations of iterator are next and hasNext. The next elements return the successive element and hasNext checks whether the element is present or not.

迭代器允許用戶遍歷集合,從而訪問所有元素。 迭代器的核心操作是nexthasNext 。 next元素返回后繼元素,并且hasNext檢查該元素是否存在。

idea運行scala?For example;

例如;

Create the scala object Iterator.scala as
Iterator.scala

將scala對象Iterator.scala創建為
Iterator.scala

object Car {def main(args: Array[String]) {val car = Iterator("Santro", "Punto", "WagonR", "Polo", "Audi")while (car.hasNext) {println(car.next())}}
}

Output:

輸出:

Santro
Punto
WagonR
Polo
Audi

迭代器的長度 (Length of Iterator)

scala函數,The size or length methods can be used to find the number of the elements in the iterator.

大小或長度方法可用于查找迭代器中元素的數量。

For example,
CarLength.scala

例如,
CarLength.scala

object CarLength {def main(args: Array[String]) {val c1 = Iterator("Santro", "Punto", "WagonR", "Polo", "Audi")val c2 = Iterator("Volkswagen", "Alto", "Xylo", "Innova")println("Iterator c1 : " + c1.size)println("Length of c2 : " + c2.length)}
}

Output:

輸出:

Iterator c1 : 5
Length of c2 : 4

查找最小和最大元素 (Finding Minimum and Maximum Elements)

The it.min and it.max methods are used to find the minimum and maximum elements in the iterator.

使用it.minit.max方法查找迭代器中的最小和最大元素。

Create scala object MinMax.scala as;
MinMax.scala

將scala對象MinMax.scala創建為;
MinMax.scala

object MinMax {def main(args: Array[String]) {val m1 = Iterator(12,45,67,89)val m2 = Iterator(44,66,77,88)println("Smallest element " + m1.min )println("Largest element " + m2.max )}
}

Output:

輸出:

Smallest element 12
Largest element 88

有用的迭代器方法 (Useful Iterator Methods)

def addString(x: StringBuilder): StringBuilder → Returns the string builder x to which elements were appended.

def addString(x:StringBuilder):StringBuilder →返回附加了元素的字符串生成器x。

def buffered: BufferedIterator[X] → Creates a buffered iterator from this iterator.

def緩沖:BufferedIterator [X] →從此迭代器創建一個緩沖的迭代器。

def foreach(f: (X) => Unit): Unit → Applies a function f to all values produced by this iterator.

def foreach(f:(X)=> Unit):Unit →將函數f應用于此迭代器產生的所有值。

def indexOf(elem: Y): Int → Returns the index of the first occurrence of the specified object in this iterable object.

def indexOf(elem:Y):Int →返回指定對象在此可迭代對象中首次出現的索引。

def product: X → Multiplies the elements of this collection.

def product:X →將這個集合的元素相乘。

That’s all for Scala Option and Iterators, we will look into Scala Traits in the next tutorial.

這就是Scala Option和Iterators的全部內容,我們將在下一個教程中研究Scala特性。

翻譯自: https://www.journaldev.com/8082/scala-option-and-iterators-example

scala迭代器

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/183239.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息