【Scala】Scala ~ 基本編 / コレクション ~

■ はじめに

https://dk521123.hatenablog.com/entry/2023/03/10/193805
https://dk521123.hatenablog.com/entry/2023/03/12/184331

の続き。

今回は、配列やコレクションについて扱う。

試す環境
https://scastie.scala-lang.org/CEpZy3v4Taa0MCStp3LCYg

目次

【0】使用上の注意
【1】配列 - Array
【2】リスト - Seq
 1)操作
【3】集合 - Set
【4】キーバリュー - Map
【5】タプル - Tuple

【0】使用上の注意

* 可変 (mutable) コレクション/不変 (immutable) コレクションがある

【1】配列 - Array

// Pattern1
val array = Array(1, 2, 3)
for (x <- array) {
  println(x)
}

// Pattern2
val helloWorlds: Array[String] = new Array[String](3)
helloWorlds(0) = "Hello"
helloWorlds(1) = ", "
helloWorlds(2) = "world"

for (helloWorldValue <- helloWorlds) {
  print(helloWorldValue)
}

【2】リスト - Seq

val hellos = Seq("Hello", "World", "!!")
for (hello <- hellos) {
  println(hello)
}
val byes = Seq("Bye", "Good night", "...")
println(byes(0))

println("*****")

// ++ : 結合
val newValues = hellos ++ byes
for (newValue <- newValues) {
  println(newValue)
}

val list = Seq(1, 2, 3, 4, 5)
println(list.updated(2, 5)) // ArrayBuffer(1, 2, 5, 4, 5)
println(list.map { case 2 => 5; case x => x }) // ArrayBuffer(1, 5, 3, 4, 5)
println(list) // ArrayBuffer(1, 2, 3, 4, 5) <= listの値自体は変わっていない

1)操作

文法 説明 備考
:+ コレクションの最後に要素を追加
+: コレクションの最初に追加 ::でもいい
++ コレクション同士の結合 ::: でもいい

https://tamura70.gitlab.io/lect-prolang/scala/scala-list.html
https://docs.scala-lang.org/ja/overviews/collections/seqs.html

サンプル

import scala.util.control.Breaks._
import scala.collection.immutable
// import scala.collection.mutable

object  Hello {
  def main(args: Array[String]) {
    var count: Int = 0
    var seq = Seq[Int]()
    breakable {
      println("Start")
      while (true) {
        count = count + 1
        println(s"count = ${count}")
        seq = seq :+ count
        if(count == 5) {
          break
        }
      }
    }
    println(s"Done. seq=${seq}")
  }
}

2)filter(抽出) / filterNot(除外)

object  Hello {
  def main(args: Array[String]) {
    println("Start")
    val targetList = Seq("b111111", "aaaa1111", "123443", "xxxxxxx")
    val regex = """^([a-zA-Z]\d{6})""".r
    val results = targetList.filter {
      x => regex.findFirstIn(x).isDefined
    }
    println(s"Done. ${results}") // List(b111111)
  }
}

https://stackoverflow.com/questions/27942480/using-regex-with-filter-in-scala

【3】集合 - Set

* 重複値は排除

サンプル

val fruits = Set("apple", "orange", "peach", "banana")
// apple? = true
println("apple? = " + fruits("apple"))
// melon? = false
println("melon? = " + fruits("melon"))

【4】キーバリュー - Map

サンプル

var helloWorldMapper = Map(1->"Hello", 2->"Hi", 3->"Bye")

// キーが2の値を取得する => "Hi"
println(helloWorldMapper(2))
// ない値はエラー
// println(helloWorldMapper(4))

// 値が存在すればSome(値) => Some(Hi)
println(helloWorldMapper.get(2))
// 存在しなければNothingを返す => None
println(helloWorldMapper.get(4))

【5】タプル - Tuple

* 複数の型の組み合わせ
 => コレクションではないけど。。。

https://qiita.com/f81@github/items/a8419532c316d190782d
使用上の注意

* タプルは、Max22個まで要素を格納できる
 => 23個指定するとエラー

サンプル

// Pattern1
val tuple = (1, "Mike", 27)
// (tuple_1=,1)
println("tuple_1=", tuple._1)
// (tuple_2=,Mike)
println("tuple_2=", tuple._2)
// (tuple_3=,27)
println("tuple_3=", tuple._3)

// Pattern2
type DemoTuple = (Int, Int, Int)
val obj: DemoTuple = (1, 22, 333)
println(s"_1 = ${obj._1}")
println(s"_2 = ${obj._2}")
println(s"_3 = ${obj._3}")

関連記事

Scala ~ 環境構築編 ~
https://dk521123.hatenablog.com/entry/2023/03/10/193805
Scala ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2023/03/12/184331
Scala ~ 基本編 / クラス ~
https://dk521123.hatenablog.com/entry/2023/03/14/000857
ScalaYAML
https://dk521123.hatenablog.com/entry/2023/03/16/012034