Scala collection library的groupBy方法
groupBy方法定义
[scala]
def groupBy [K] (f: (A) ⇒ K): Map[K, Traversable[A]]
[/scala]
demo 1
[scala]
val birds = List("Golden Eagle", "Gyrfalcon", "American Robin",
"Mountain BlueBird", "Mountain-Hawk Eagle")
val groupedByFirstLetter = birds.groupBy(_.charAt(0))
[/scala]
结果
Map(
M -> List(Mountain BlueBird, Mountain-Hawk Eagle),
G -> List(Golden Eagle, Gyrfalcon),
A -> List(American Robin)
)
demo2
[scala]
val cats = List("Tiger", "Lion", "Puma", "Leopard", "Jaguar", "Cheetah", "Bobcat")
val groupedByLength = cats.groupBy(_.length)
[/scala]
结果
Map(
5 -> List(Tiger),
7 -> List(Leopard, Cheetah),
4 -> List(Lion, Puma),
6 -> List(Jaguar, Bobcat)
)
demo 3
[scala]
val raptors = List("Golden Eagle", "Bald Eagle", "Prairie Falcon", "Peregrine Falcon", "Harpy Eagle", "Red Kite")
val kinds = raptors.groupBy {
case bird if bird.contains("Eagle") => "eagle"
case bird if bird.contains("Falcon") => "falcon"
case _ => "unknown"
}
[/scala]
结果
Map(
unknown -> List(Red Kite),
eagle -> List(Golden Eagle, Bald Eagle, Harpy Eagle),
falcon -> List(Prairie Falcon, Peregrine Falcon)
)
demo 4
[scala]
val words = List("one", "two", "one", "three", "four", "two", "one")
val counts = words.groupBy(w => w).mapValues(_.size)
[/scala]
结果
Map(one -> 3, two -> 2, four -> 1, three -> 1)
demo 5
[scala]
val numbers = List(1,4,5,1,6,5,2,8,1,9,2,1)
numbers.groupBy(x=>x).map {x=> (x._1, x._2.length) }
[/scala]
结果和demo 4一样
Map[Int,Int] = Map(5 -> 2, 1 -> 4, 6 -> 1, 9 -> 1, 2 -> 2, 8 -> 1, 4 -> 1)