How to convert list of integers to a map with frequency per bin?

爷,独闯天下 提交于 2019-12-07 09:01:17

问题


Lets say I have a list of numbers:

val numbers = List(15, 30, 110, 140, 170, 210)

How can I count the number of integers per bin of a 100 in order to get:

Map(0 -> 2, 100 -> 3, 200 -> 1)

回答1:


scala> List(1,2,3,101,330,302).groupBy(i => i/100)
                              .map {case (i,l) => (i*100,l.length)}
res1: scala.collection.immutable.Map[Int,Int] = Map(100 -> 1, 300 -> 2, 0 -> 3)



回答2:


Starting Scala 2.13, you can use the groupMapReduce method which is (as its name suggests) an equivalent of a groupBy followed by a map and a reduce step on values:

// val items = List(1, 2, 3, 101, 330, 302)
items.groupMapReduce(_ / 100 * 100)(_ => 1)(_ + _)
// Map(0 -> 3, 100 -> 1, 300 -> 2)

This:

  • groups items by their associated "bin" (_ / 100 * 100 e.g. 330 / 100 * 100 = 300) (group part of groupMapReduce)

  • maps grouped values to 1 (_ => 1) (map part of groupMapReduce)

  • reduces values within each group (_ + _) by summing them (reduce part of groupMapReduce).

This is a one-pass version of what can be translated by:

items.groupBy(_ / 100 * 100).mapValues(_.map(_ => 1).reduce(_ + _)).toMap


来源:https://stackoverflow.com/questions/20442534/how-to-convert-list-of-integers-to-a-map-with-frequency-per-bin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!