Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
13
Help us understand the problem. What is going on with this article?
@f81@github

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

More than 5 years have passed since last update.

# 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
``````

## 追加

### +

``````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)
``````

ここでようやく重複排除をみることができたね。

### ++

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

## 削除

### -

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

### --

``````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)
``````

# まとめ

どのような場面で使うかを想像しながら、ソースを書いて動かしてみてね。

13
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away
Fringe81のエンジニアが頑張って執筆ちゅうです！ Scala の修行を始めました。 みなさま、温かい目で見守ってください。
Fringeは、最新のテクノロジーとプロフェッショナルによるサービスにより、社会課題に仮説を立てて市場に広げていくことで、数十年という長期的なスパンで価値を生み出し続け、より良い世界を創る集団です。 既存の領域に限らず、時流を読み、仮説を生み出し、テクノロジーの力で優れたサービスを生み出し続けます。