ScalaにおけるSetの基本的な使用方法を見ていきます。
Setの基本的な使い方
Scala Setの基本的な使い方
def main(args: Array[String]) : Unit = {
val set = Set("a", "b" , "c" , "c") // Setの定義
println(set) // Set(a, b ,c) 重複は削除される
// 要素を含むかを検証
println(set.contains("a")) // true
println(set.contains("d")) // false
println(set("a")) // set.contains("a") と同じ
// 要素の追加
println(set + "d") // Set(a, b, c, d)
println(set ++ Set("d", "e")) // HashSet(e, a, b, c, d)
}
可変なSetに対する操作
Setは基本的には変更不可能なクラスです。
しかし、 scala.collection.mutable.Set を使用することで、変更可能なSetを使用することができます。
immutable.Setのサンプル
import scala.collection.mutable
object Sample {
def main(args: Array[String]) : Unit = {
val set = mutable.Set(1,2,3)
// 追加
set += 4 // HashSet(1, 2, 3, 4)
set += (5, 6) // HashSet(1, 2, 3, 4, 5, 6)
// addは含まれていない場合true, 既に追加済みならfalseを返す
set add 7 // ture, HashSet(1, 2, 3, 4, 5, 6, 7)
set add 7 // false, HashSet(1, 2, 3, 4, 5, 6, 7)
// 削除
set -= 7 // HashSet(1, 2, 3, 4, 5, 6)
set -= (6, 5) // HashSet(1, 2, 3, 4)
set remove 4 // true, HashSet(1, 2, 3, 4)
set remove 4 // false, HashSet(1, 2, 3, 4)
}
}
参考