0
点赞
收藏
分享

微信扫一扫

Scala 复习笔记

_鱼与渔_ 2024-04-19 阅读 27

元组:

元素类型一致 存取有序可重复 Seq

​ 无序不可重复 Set

​ 键值对 Map (存储的就是Tuple2 ,对偶元组)

元素类型不一致 Tuple (至多22个元素)

代码: 定义 拆分 函数返回元组类型 遍历 productIterator返回的元素是Any类型。 isInstanceOf asInstanceOf 元组嵌套 调用元组中的元素

val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

数组,集合(通用的方法。 要明白上边的list执行下面的每个方法分别是什么效果)

toList toSet toArray toMap

Map转为List 等,元素类型为Tuple2. 其他的要转Map,元素类型必须是Tuple2

head last tail init reverse(set集合无序,可以翻转吗) take takeRight

drop dropRight takeWhile deopWhile

衍生集合, list.zip(set).tomap ._1为key , ._2为value

集合切分 splitAt 列表一分为二,放入Tuple中 slice sliding

reduce reduceRight fold()() foldRight

sum product max min

sortBy map中按key 。 maxBy minBy

filter map groupBy flatten

// 统计集合中出现次数最多的前三名
val list = List("hello amy" , "from hadoop" ,"hello from","hello hadoop")

val top3 = list.flatMap(_.split(" "))
  .groupBy(x => x)
  // map无序 ,转为list
  .map(t => (t._1 ,t._2.size))
  .toList.sortBy(_._2)(Ordering.Int.reverse)
  .take(3)

//统计每一个单词出现的次数
val list1 = List("hello" -> 5 , "hi" -> 3 ,"hello" -> 6)
val groupBy = list1.groupBy(_._1)
// 元组无法扁平化
groupBy.map(
  t => (
    t._1 ,
    //元素reduce前后的类型要一致
    t._2.reduce(
      (x,y) =>( x._1 ,x._2 + y._2)
    )._2
  )
)
举报

相关推荐

0 条评论