Reputation: 33
I am new in scala. and I want to get below size of element from ArraySeq(Split by comma)
ArraySeq(A,B,C,D) // 4
ArraySeq(A,B,C)) // 3
ArraySeq(A,B)) //2
ArraySeq(A,B,C,D,E)) // 5
Also I would like to access each element from ArraySeq.
Does anyone can help me out of that?
Upvotes: 0
Views: 292
Reputation: 449
You can use .size
on any of the scala collections.
e.g. scala ArraySeq(A,B,C,D).size
would return 4
There are a few ways to go about accessing the elements of the sequence
val example = ArraySeq(1,2,3,4,5)
// Using the apply method
example(1) // Result 2
example(10) // ArrayIndexOutOfBoundsException is thrown
// Using .get to avoid exceptions
example.get(2) // Result Some(3)
example.get(10) // Result None
// You can transform all elements using map
example.map(_ * 2) // Result ArraySeq(2,4,6,8,10)
// Or do something with all elements
example.foreach(println) // prints 1,2,3,4,5 separated by newlines
If you have a nested ArraySeq (i,e, ArraySeq[ArraySet[T]]) you can get the total size using:
val exampleNested = ArraySeq(ArraySeq(1,2),ArraySeq(3,4,5), ArraySeq(6,7,8))
exampleNested.map(_.size).sum // Returns total size of 8
You can also flatten the nested collections to a single array seq for ease of use with
exampleNested.flatten // Result ArraySeq(1, 2, 3, 4, 5, 6, 7, 8)
Upvotes: 1