Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple items from a list, given their indices?

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?

like image 621
user3195418 Avatar asked Dec 05 '22 03:12

user3195418


1 Answers

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 on List, there are several shorthand expressions of this logic:

val indices = List(0, 1)
indices.map(index => list.apply(index))
indices.map(index => list(index))
indices.map(list(_))
indices.map(list)
indices map list

It's worth noting that since these are all maps on indices, the resulting collection will generally have the same type as indices, and not list:

val list = Array(1, 2, 3)
val indices = List(0, 1)
indices map list //List(1, 2), instead of Array(1, 2)

This can be an undesirable property here. One solution to this is to use breakOut (in scala.collection):

val newList: Array[Int] = indices.map(list)(breakOut)

You can read more about breakOut here. The following solutions also maintain the collection type of list when possible by performing operations on list instead of indeces:

If you are looking for a contiguous range of the list, you might consider using slice:

list.slice(1, 2) //List(2)

You could also use drop and take (and the dropRight, takeRight versions) to a similar effect:

list.drop(1).take(1)

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:

list.zipWithIndex.collect { 
    case(el, index) if indices.contains(index) /* any other logic */ => el 
}
like image 90
Ben Reich Avatar answered Feb 23 '23 00:02

Ben Reich