Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element from Set

Tags:

scala

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

like image 314
blue-sky Avatar asked Jul 04 '14 09:07

blue-sky


People also ask

How do you select an element from a Set in Python?

We can access the first item in the set by using the iter() function, we have to apply the next() to it to get the first element. We can also use the first() method from the iteration_utilities module, Which will return the first element.

Does Set have get method?

Set would require extra code to be able to keep track of an order. Note that there is a Set implementation that does keep track of insertion order--LinkedHashSet--but it doesn't have a get() method.

How do you access elements of collections?

It has 3 methods: boolean hasNext(): This method returns true if the iterator has more elements. elements next(): This method returns the next elements in the iterator. void remove(): This method removes from the collection the last elements returned by the iterator.


1 Answers

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
like image 145
senia Avatar answered Oct 05 '22 20:10

senia