Select first 'N' items from map in Scala

Is there an elegant way to extract the first "N" elements from a map?

I can create a new map and iterate over the values ​​that need to be selected, is there a function that does this?

+6
source share
3 answers

From the docs for the take method on Map :

Selects the first n items.

Note: may return different results for different runs, provided that the base collection type is ordered.

In the case of maps, the collection is not ordered, so do not expect to receive the first n elements - in fact, the concept of the first n elements does not even exist for mappings.

But take will provide you with the first few n elements, and it looks 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 need to get two elements that are included in the definition, but do not count on it.

+13
source
 scala> val map = Map[String,Int]("one"->1,"two"->2,"three"->3) map: scala.collection.immutable.Map[String,Int] = Map(one -> 1, two -> 2, three -> 3) scala> val n = 2 n: Int = 2 scala> val firstN = map.take(n) firstN: scala.collection.immutable.Map[String,Int] = Map(one -> 1, two -> 2) 
0
source

It looks like you are looking for a SortedMap along with take(n) as discussed by others.

0
source

Source: https://habr.com/ru/post/950910/


All Articles