Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first 'N' elements from map in Scala

Tags:

scala

Is there an elegant method of extracting first 'N' elements from a Map ?

I could create a new Map and iterate over the values that are to be selected, is there a function that accomplishes this ?

like image 741
blue-sky Avatar asked Aug 02 '13 13:08

blue-sky


1 Answers

From the docs for the take method on Map:

Selects first n elements.

Note: might return different results for different runs, unless the underlying collection type is ordered.

In the case of maps the collection isn't ordered, so don't count on getting the first n elements—in fact the concept of the first n elements doesn't even exist for maps.

But take will give you some first n elements, and it sounds like this is what you want:

scala> Map('a -> 1, 'b -> 2, 'c -> 3).take(2)
res1: scala.collection.immutable.Map[Symbol,Int] = Map('a -> 1, 'b -> 2)

In this case you happen to get the two elements that came first in the definition, but don't count on this happening.

like image 128
Travis Brown Avatar answered Oct 01 '22 10:10

Travis Brown