what's the difference between Seq and Set in Scala
Asked Answered
D

4

8
var seq = Seq[String]()
seq = seq :+ "hello"

var set = Set[String]()
set += "hello"

what's the difference between Seq and Set?

Drowsy answered 6/11, 2013 at 2:48 Comment(0)
C
11

Seq

http://www.scala-lang.org/api/current/scala/collection/Seq.html

Sequences always have a defined order of elements. Sequences provide a method apply for indexing.

Seq is similar to java.util.List.

Set

http://www.scala-lang.org/api/current/scala/collection/Set.html

A set is a collection that contains no duplicate elements.

This closely resembles a "set" in the mathematical sense: http://en.wikipedia.org/wiki/Set_(mathematics)

Set is similar to java.util.Set.

Cenac answered 6/11, 2013 at 3:0 Comment(0)
O
7

This is described in many places, such as the documentation for Seq and Set and Scala's Collection Library guide.

One could also describe them by their characteristic functions:

  • A Set[A] is a function A => Boolean, which means one can check whether an element is present on it or not.

  • A Seq[A] is a function Int => A, which means that each element in it has an index, and one can retrieve the element that is at any given index.

This also explains the difference between the two statements:

seq = seq :+ "hello"
seq = "hello" +: seq 

set = set + "hello"

On a Set, one doesn't control the ordering of elements, so you simply add elements to it. On a Seq, because each element has an index, it is relevant where the element is being placed, and so we have +: and :+, which specify, respectively, that an element is to be prepended or appended to the sequence.

Oho answered 6/11, 2013 at 3:4 Comment(0)
S
2

Asked myself this question and Scala worksheet provided an answer :

val seq = Seq(1,1)                   //> seq  : Seq[Int] = List(1, 1)
val set = Set(1,1)                   //> set  : scala.collection.immutable.Set[Int] = Set(1)

One noticeable difference is that Seq allows duplicates, while Set does not.

Shelby answered 28/5, 2014 at 21:31 Comment(0)
A
1

a set is a collection where you store distinct values while a seq is a more generalized version of collection its common superclass for some often used collections like Array,List etc..

in your example:

var set = Set[String]()
set += "hello"

set contains "hello"

set += "hello"

-> set remains unchanged.

for further information see the api on set : http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Set

Aflame answered 6/11, 2013 at 2:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.