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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With