blue-sky
blue-sky

Reputation: 53806

Get element from Set

How can I get element at position in Set ?

For a List can do :

  val s : Set[(String, String)] = Set( ("a","b") )
  val l1 = l(0)

But for Set :

  val s : Set[(String, String)] = Set( ("a","b") )
  val t1 = s(1)

I get compile time error :

Multiple markers at this line - type mismatch; found : Int(1) required: (String, String) - type mismatch; found : 
 Int(1) required: (String, String)

Update :

converting to List is an option but I though should be able to access a element at position in Set

Upvotes: 10

Views: 22926

Answers (1)

senia
senia

Reputation: 38045

Set is not an ordered collection - you can't get element by index.

You could use head method to get single element from Set (it's not the first element, just some element).

You could also process all elements using foreach method:

for (s <- Set("a", "b")) println(s)

If you want to get all elements in some order you should convert Set to Seq using toSeq method like this:

val mySeq = mySet.toSeq

Upvotes: 24

Related Questions