Scala collection library的groupBy方法

groupBy方法定义

def groupBy [K] (f: (A) ⇒ K): Map[K, Traversable[A]]

demo 1

val birds = List("Golden Eagle", "Gyrfalcon", "American Robin",
"Mountain BlueBird", "Mountain-Hawk Eagle")
val groupedByFirstLetter = birds.groupBy(_.charAt(0))

结果
Map(
M -> List(Mountain BlueBird, Mountain-Hawk Eagle),
G -> List(Golden Eagle, Gyrfalcon),
A -> List(American Robin)
)

demo2

val cats = List("Tiger", "Lion", "Puma", "Leopard", "Jaguar", "Cheetah", "Bobcat")
val groupedByLength = cats.groupBy(_.length)

结果
Map(
5 -> List(Tiger),
7 -> List(Leopard, Cheetah),
4 -> List(Lion, Puma),
6 -> List(Jaguar, Bobcat)
)

demo 3

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"
}

结果
Map(
unknown -> List(Red Kite),
eagle -> List(Golden Eagle, Bald Eagle, Harpy Eagle),
falcon -> List(Prairie Falcon, Peregrine Falcon)
)

demo 4

val words = List("one", "two", "one", "three", "four", "two", "one")
val counts = words.groupBy(w => w).mapValues(_.size)

结果
Map(one -> 3, two -> 2, four -> 1, three -> 1)

demo 5

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) }

结果和demo 4一样
Map[Int,Int] = Map(5 -> 2, 1 -> 4, 6 -> 1, 9 -> 1, 2 -> 2, 8 -> 1, 4 -> 1)

发表评论

电子邮件地址不会被公开。