Scala常见操作总结
Scala常见操作总结
文章目录
1. groupBy
groupBy方法定义
1 | def groupBy [K] (f: (A) ⇒ K): Map[K, Traversable[A]] |
(1)案例1
1 | val birds = List("Golden Eagle", "Gyrfalcon", "American Robin", "Mountain BlueBird", "Mountain-Hawk Eagle") |
输出
1 | Map(M -> List(Mountain BlueBird, Mountain-Hawk Eagle), G -> List(Golden Eagle, Gyrfalcon), A -> List(American Robin)) |
(2)案例2
1 | val cats = List("Tiger", "Lion", "Puma", "Leopard", "Jaguar", "Cheetah", "Bobcat") |
输出
1 | Map(5 -> List(Tiger), 4 -> List(Lion, Puma), 7 -> List(Leopard, Cheetah), 6 -> List(Jaguar, Bobcat)) |
(3)案例3
1 | val raptors = List("Golden Eagle", "Bald Eagle", "Prairie Falcon", "Peregrine Falcon", "Harpy Eagle", "Red Kite") |
输出
1 | Map(eagle -> List(Golden Eagle, Bald Eagle, Harpy Eagle), falcon -> List(Prairie Falcon, Peregrine Falcon), unknown -> List(Red Kite)) |
(4)案例4
1 | val strList=List("aaa","bbb","ccc","bbb","ccc") |
输出
1 | Map(ccc -> List(ccc, ccc), bbb -> List(bbb, bbb), aaa -> List(aaa)) |
(5)案例5
1 | val words = List("one", "two", "one", "three", "four", "two", "one") |
输出
1 | Map(one -> 3, three -> 1, four -> 1, two -> 2) |
(6)案例6
1 | val numbers = List(1,4,5,1,6,5,2,8,1,9,2,1) |
输出
1 | Map(5 -> 2, 1 -> 4, 6 -> 1, 9 -> 1, 2 -> 2, 8 -> 1, 4 -> 1) |