天天看点

【scala初学】collections Sets

【scala初学】collections Sets

Set,与Seq, Map并列

Set是没有重复元素的Iterable,方法分为如下几类:

Test 

方法:<code>contains</code>, <code>apply</code>, <code>subsetOf</code>

<code>   contains方法询问是否set包含了yield被给与的元素.</code>

<code>   apply同contains,即 set(elem) 等同于 set contains elem</code>

For example

1

2

3

4

5

6

<code>scala&gt; </code><code>val</code> <code>fruit </code><code>=</code> <code>Set(</code><code>"apple"</code><code>, </code><code>"orange"</code><code>, </code><code>"peach"</code><code>, </code><code>"banana"</code><code>)</code>

<code>fruit</code><code>:</code> <code>scala.collection.immutable.Set[java.lang.String] </code><code>=</code> <code>Set(apple, orange, peach, banana)</code>

<code>scala&gt; fruit(</code><code>"peach"</code><code>)</code>

<code>res</code><code>0</code><code>:</code> <code>Boolean </code><code>=</code> <code>true</code>

<code>scala&gt; fruit(</code><code>"potato"</code><code>)</code>

<code>res</code><code>1</code><code>:</code> <code>Boolean </code><code>=</code> <code>false</code>

<code>Additions</code>

方法:<code>+</code> and <code>++</code>

<code>   增加一个或者多个元素</code>

<code>Removals</code>

<code>方法: - , --</code>

<code>   删除一个或者多个元素</code>

Set operations

  方法:union, intersection, diff

   这些方法有两种形式,字母和字符。

intersect

&amp;

union

|

diff

&amp;~

 继承自Traversable的++方法有点类似unoin。(后面略,没意义)

Class Set 操作

WHAT IT IS

WHAT IT DOES

Tests:

xs contains x

测试 xs是否包含x

xs(x)

同上

xs subsetOf ys

测试xs是否是ys的子集

Additions:

xs + x

Set xs 添加元素x ,返回Set(子类可能重写)

xs + (x, y, z)

Set xs 添加括号中的元素 返回Set

xs ++ ys

xs ys合并后的所有元素 返回 Set

Removals

xs - x

Set 包含xs中除去x的所有元素

xs - (x, y, z)

Set 包含xs出去括号中元素的所有元素

xs -- ys

Set 包含xs中除去ys中元素的所有元素

xs.empty

清空xs

Binary Operations:

xs &amp; ys

xs和ys的交集

xs intersect ys

xs | ys

xs和ys的并集

xs union ys

xs &amp;~ ys

xs和ys的区别

xs diff ys

<code></code>

本文转自 wws5201985 51CTO博客,原文链接:http://blog.51cto.com/yjplxq/1432320,如需转载请自行联系原作者