Let's say, I have a list. If I want to return something at the index of that list, I can just pass the lists' val, the index. Like so.
val list = List(1, 2, 3)
list(0) //Int = 1
But what if I want items at multiple indexes on this list? I want to be able to do this... list(0, 1)
and get a collection of the items at those indices.
This is crazily simple in Ruby. Anyone have any suggestions?
You can flip the logic around, so that for each index, you're getting the index, you retrieve the element at that index. Since you are using the
apply
method onList
, there are several shorthand expressions of this logic:It's worth noting that since these are all
maps
onindices
, the resulting collection will generally have the same type asindices
, and notlist
:This can be an undesirable property here. One solution to this is to use
breakOut
(inscala.collection
):You can read more about breakOut here. The following solutions also maintain the collection type of
list
when possible by performing operations onlist
instead ofindeces
:If you are looking for a contiguous range of the list, you might consider using
slice
:You could also use
drop
andtake
(and thedropRight
,takeRight
versions) to a similar effect:For more complex versions of this type of filtering, you might be interested in the
zipWithIndex
method, which would allow you to express arbitrary logic on the index: