LoginSignup
19
14

More than 5 years have passed since last update.

第12章:ScalaのSetリファレンス

Last updated at Posted at 2013-10-01

今回は「Set」について、リファレンス風に紹介するよ!

入門編としてこちらも読んでね(^^)v
第8章:Scalaのコレクション(Seq, Set, Map)入門

scala.collection.immutable.Set

集合を現す箱。
要素の重複を許さない箱だ。

よって、要素の重複をなくしたり、存在判定をするときに使えるね。

テスト

(x)

xが存在するか判定する

scala> Set(1, 2, 3)(2)
res0: Boolean = true

scala> Set(1, 2, 3)(4)
res1: Boolean = false

contains

(x)と同じ

scala> Set(1, 2, 3) contains(2)
res2: Boolean = true

scala> Set(1, 2, 3) contains(4)
res3: Boolean = false

subsetOf

部分集合か判定する

scala> Set(1, 2) subsetOf Set(1, 2, 3)
res4: Boolean = true

scala> Set(3, 4) subsetOf Set(1, 2, 3)
res5: Boolean = false

追加

+

指定した要素を追加した新しいSetを返す

scala> Set(1, 2, 3) + 4
res6: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4)

scala> Set(1, 2, 3) + 3
res7: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

ここでようやく重複排除をみることができたね。
既に要素3がSetに存在しているので、3を追加しても
複数の要素が存在することはないんだよ!

++

指定したSetを追加した新しいSetを返す

scala> Set(1, 2, 3) ++ Set(4, 5)
res8: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)

削除

-

指定した要素を削除した新しいSetを返す

scala> Set(1, 2, 3) - 3
res9: scala.collection.immutable.Set[Int] = Set(1, 2)

--

指定したSetを削除した新しいSetを返す

scala> Set(1, 2, 3) -- Set(1, 2)
res10: scala.collection.immutable.Set[Int] = Set(3)

empty

空集合を返す

scala> val set = Set(1, 2, 3)
set: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

scala> set empty
res11: scala.collection.immutable.Set[Int] = Set()

scala> set
res12: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

二項演算

&

積集合を返す

scala> Set(1, 2, 3) & Set(1, 5)
res13: scala.collection.immutable.Set[Int] = Set(1)

intersect

&と同じ

scala> Set(1, 2, 3) intersect Set(1, 5)
res14: scala.collection.immutable.Set[Int] = Set(1)

|

和集合を返す

scala> Set(1, 2, 3) | Set(1, 5)
res15: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 5)

union

|と同じ

scala> Set(1, 2, 3) union Set(1, 5)
res16: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 5)

&~

差集合を返す

scala> Set(1, 2, 3) &~ Set(1, 5)
res17: scala.collection.immutable.Set[Int] = Set(2, 3)

diff

&~と同じ

scala> Set(1, 2, 3) diff Set(1, 5)
res18: scala.collection.immutable.Set[Int] = Set(2, 3)

まとめ

今回は、 コレクションのSetトレイトのメソッドについて語ってみたけどどうだった?

過去2回と同じで、やっぱりこの辺は体を動かさないとわからないね。
どのような場面で使うかを想像しながら、ソースを書いて動かしてみてね。

今回も
体で感じてくれたかな?

19
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
14