当前位置: 代码迷 >> 综合 >> SCALA-DAY03(课堂代码)
  详细解决方案

SCALA-DAY03(课堂代码)

热度:32   发布时间:2023-11-30 10:44:20.0

集合常用函数

1 forEach 

package com._51doit.day03.demo/*** FileName: ForEachDemo* Author:   多易教育-DOIT* Date:     2020/11/2 0002* Description:* 对集合中的每个元素处理    适用所有的集合类型*  Array*  List*  Iterator*  Set*  Map*  注意 : 方法是没有返回值   常用于打印测试*/
object ForEachDemo {def main(args: Array[String]): Unit = {val ls = List(1,2,3,4)val mp = Map[String,Int](("a",1),"b"->2,"c"->3)// listls.foreach(e=>println(e))ls.foreach(e=>println(e*10))ls.foreach(println(_))ls.foreach(println)ls.foreach(e=>print(e+" "))// 映射集合  Mapmp.foreach(tp=>println(tp))mp.foreach(tp=>println(tp._1))mp.foreach(tp=>println(tp._2))/* mp.foreach(tp =>{tp._1tp._2})*//* ls.foreach(e=>{val res: Int = e * 100 + 10println("hello"+res)res})*/}}

2 map

package com._51doit.day03.demoimport scala.collection.immutable/*** FileName: MapDemo* Author:   多易教育-DOIT* Date:     2020/11/2 0002* Description:* map函数和 foreach类似 对集合中的每个元素处理* 适用范围是所有的集合类型** 注意:接收返回值  也可以适用for循环的推导式来实现接收返回值*/
object MapDemo {def main(args: Array[String]): Unit = {val ls = List(1, 2, 3, 4)val mp = Map[String, Int](("a", 1), "b" -> 2, "c" -> 3)// 对list集合中的每个元素处理:每个元素*10  将处理后的每个元素用一个新的集合来接收val ls2: List[Int] = ls.map(e => e * 10)// 可以嵌套的val ls3: List[Int] = for (elem <- ls) yield elem * 10/* val mp2: Map[String, Int] = mp.map(ele => {val newK: String = ele._1.toUpperCaseval newV: Int = ele._2 * 100(newK, newV)})*/mp.map(ele => {val newK: String = ele._1.toUpperCaseval newV: Int = ele._2 * 100(newK, newV)}).foreach(println)//处理每个元素 返回的数据结构没有变化mp.map(e => {(e._1.toUpperCase, e._2 * 100)})// 返回的数据结构  只返回vval ints: immutable.Iterable[Int] = mp.map(e => e._2)// 处理的数据返回的数据结构结构  4个元素的元祖组成的迭代器val res = mp.map(e => {(e._1, e._1.toUpperCase, e._2, e._2 * 10)}).foreach(e => println(e._2))//ls.map(e => e * 10).foreach(println)}}

3 filter和filterNot

package com._51doit.day03.demo/*** FileName: FilterDemo* Author:   多易教育-DOIT* Date:     2020/11/2 0002* Description:* 将集合中符合条件的元素筛选出 放在新的集合中*/
object FilterDemo {def main(args: Array[String]): Unit = {val ls   =  List[Int](1,2,3,4,5,6,7,8,9)val arr = Array("tom" , "jim" , "cat","jack")val  mp = Map[String,Int]("a"->1,"java"->23,"js"->33,"sql"->21)// 过滤出大于5val res1: List[Int] = ls.filter(e => e > 5)// 偶数ls.filter(_%2==0)//多条件过滤   &&ls.filter(e=> e%2==0 && e>5)// 多条件的  多次调用filterls.filter(_%2==0).filter(_>5).foreach(println)// arrayval res2: Array[String] = arr.filter(_.startsWith("j"))// res2.foreach(println)arr.filter(e=>e.startsWith("j")&&e.length>3)arr.filter(_.startsWith("j")).filter(_.length>3)// Map集合val res3: Map[String, Int] = mp.filter(tp => tp._1.startsWith("j"))// res3.foreach(println)mp.filter(tp => tp._1.startsWith("j") && tp._2>30)mp.filter(_._1.startsWith("j")).filter(_._2>30).foreach(println)}
}
package com._51doit.day03.demo/*** FileName: FilterNotDEmo* Author:   多易教育-DOIT* Date:     2020/11/2 0002 * Description:* 将集合中不符合条件的元素筛选出 放在新的集合中*/
object  FilterNotDemo {def main(args: Array[String]): Unit = {val ls   =  List[Int](1,2,3,4,5,6,7,8,9)val arr = Array("tom" , "jim" , "cat","jack")val  mp = Map[String,Int]("a"->1,"java"->23,"js"->33,"sql"->21)ls.filterNot(_>4).foreach(println)  // <=4}
}

案例

package com._51doit.day03.demo.test1/*** FileName: TestFIlter* Author:   多易教育-DOIT* Date:     2020/11/2 0002* Description:* 1 集合可以嵌套* 2 isEmpty  集合没有元素   String为 ""* 3 trim  去除空白*/
object TestFIlter {def main(args: Array[String]): Unit = {val mp = Map[String, Array[String]](("sl", Array("ts", "zbj", "hhs", "shaseng")),("em", Array()),("gb", Array("hg", "tg")))// mp.filter(tp=>tp._2.length>0).foreach(tp=>println(tp._1+" "+tp._2.toList))// 非空数组// mp.filter(tp=> !tp._2.isEmpty).foreach(tp=>println(tp._1+" "+tp._2.toList))val ls = List("abc", "java", "", "\t\t ")// ls.filter(!_.isEmpty)println(ls.filter(e => !e.trim.isEmpty).length)}}

4 collect

package com._51doit.day03.demo/*** FileName: CollectDemo* Author:   多易教育-DOIT* Date:     2020/11/2 0002* Description:* collect对每个元素进行操作  支持偏函数(接口)*/
object CollectDemo {def main(args: Array[String]): Unit = {val ls = List[Any](1, 2, 3, 4, 5, 6, 7, "hello", "jim")// 偏函数   对集合中的某一中数据类型处理  偏爱val pf = new PartialFunction[Any, Int] {// 集合中的每个元素override def isDefinedAt(x: Any): Boolean = {// 返回true 和false  指定Int的类型truex.isInstanceOf[Int]}// 上面方法返回true的时候 指定这个方法override def apply(v1: Any): Int = { // 1 2 3 4 5 6 7v1.asInstanceOf[Int] *10}}// 遍历每个元素  ->1 (isDefinedAt)-->(apply)--10 -->新的集合中ls.collect(pf).foreach(println)// ls.map(pf).foreach(println)}
}

5 mapValues

package com._51doit.day03.demo/*** FileName: MapValuesDemo* Author:   多易教育-DOIT* Date:     2020/11/2 0002* Description:* 针对Map集合的value操作*/
object MapValuesDemo {def main(args: Array[String]): Unit = {val mp = Map[String,List[Int]]("zss"->List(1,3,5,7) , "lss"->List(2,4,6,8))val res: Map[String, Int] = mp.mapValues(ls => ls.sum)res.foreach(println)}}

6 groupBy 

package com._51doit.day03.demoimport java.io.Fileimport scala.io.{BufferedSource, Source}/*** FileName: GroupByDemo* Author:   多易教育-DOIT* Date:     2020/11/2 0002* Description: */
object GroupByDemo {def main(args: Array[String]): Unit = {// 读取数据   获取单词  将单词组装成 (单词,1)val bs: BufferedSource = Source.fromFile(new File("d://word.txt"))val strings: Iterator[String] = bs.getLines()// 所有的单词val words: Iterator[String] = strings.flatMap(_.split("\\s+"))//将单词组装成 (单词,1)//val wordAndOne: Iterator[(String, Int)] = words.map(word => (word, 1))val wordAndOne: Iterator[(String, Int)] = words.map((_, 1))// 将相同的单词分组    groupBy 方法适用于Map集合val list: List[(String, Int)] = wordAndOne.toList// 按照单词  单词相同的分到一组// hello ,  List((hello,1),(hello,1))val res: Map[String, List[(String, Int)]] = list.groupBy(_._1)val res2: Map[String, (String, Int)] = res.mapValues(ls => {val sum: Int = ls.map(_._2).sum("", sum)})//res2.map(tp=>(tp._1 , tp._2._2)).foreach(println)val res3: Map[String, Int] = res.mapValues(ls => {val sum: Int = ls.map(_._2).sumsum})res3.foreach(println)/* res.map(tp=>{val word: String = tp._1val count: Int = tp._2.length(word ,count)}).foreach(println)*/}}
package com._51doit.day03.demo.test1import java.io.Fileimport scala.io.Source/*** FileName: WordCount* Author:   多易教育-DOIT* Date:     2020/11/2 0002* Description: */
object WordCount {def main(args: Array[String]): Unit = {Source.fromFile(new File("d://word.txt")).getLines().flatMap(_.split("\\s+")).map((_,1)).toList.groupBy(_._1).map(tp=>(tp._1,tp._2.length))val res: Map[String, Int] = Source.fromFile(new File("d://word.txt")).getLines().flatMap(_.split("\\s+")).map((_, 1)).toList.groupBy(_._1).mapValues(tp => tp.map(_._2).sum)res.foreach(println)}}

 

7 sorted

package com._51doit.day03.demo.sortimport com._51doit.day03.demo.pojo.User/*** FileName: SortedDemo* Author:   多易教育-DOIT* Date:     2020/11/2 0002 * Description:* 对集合中的元素排序  元素可排序(有排序规则)*    排序规则 默认行为*    Int*    String  默认排序规则*/
object  SortedDemo {def main(args: Array[String]): Unit = {val arr = Array(1,23,32,21,33,35,26)arr.sorted.foreach(println)val ls =  List("apple" , "door", "bank" , "cool")ls.sorted.foreach(println)val mp = Map[String,Int]("a"->12,"c"->33,"b"->20)mp.toList.sorted.foreach(println)val users = List[User](User("zss",33),User("zss",23) ,User("lss",23),User("black",20))users.sorted.foreach(println)}}

8 sortBy

package com._51doit.day03.demo.sortimport com._51doit.day03.demo.pojo.User/*** FileName: SortedDemo* Author:   多易教育-DOIT* Date:     2020/11/2 0002 * Description:* 对集合中的元素排序  元素可排序(有排序规则)*    排序规则 默认行为*    Int*    String  默认排序规则*/
object  SortedDemo2 {def main(args: Array[String]): Unit = {val arr = Array(1,23,32,21,33,35,26)arr.sortBy(e=> -e).foreach(println)val ls =  List("apple" , "door", "bank" , "cool")ls.sortBy(_).foreach(println)  // 不好降序val mp = Map[String,Int]("a"->12,"c"->33,"b"->20)mp.toList.sortBy(_._1)mp.toList.sortBy(_._2)val userMp: Map[String, User] = Map[String, User]("a" -> User("zss", 33), "c" -> User("zss", 23), "b" -> User("lss", 23))userMp.toArray.sortBy(_._1)userMp.toArray.sortBy(_._2)userMp.toArray.sortBy(_._2.name)val lp = List((1, "zss", "F", 1200.12), (2, "lss", "F", 2212.12))lp.sortBy(-_._4)/*   val users = List[User](User("zss",33),User("zss",23) ,User("lss",23),User("black",20))users.sorted.foreach(println)*/}}

9sortWith

package com._51doit.day03.demo.sortimport com._51doit.day03.demo.pojo.User/*** FileName: SortedDemo* Author:   多易教育-DOIT* Date:     2020/11/2 0002 * Description: sortWith* 对集合中的元素排序  元素可排序(有排序规则)*    排序规则 默认行为*    Int*    String  默认排序规则*/
object SortedDemo3 {def main(args: Array[String]): Unit = {val arr = Array(1,23,32,21,33,35,26)arr.sortWith((x1,x2)=>x1>x2)arr.sortWith((x1,x2)=>x2>x1)val ls =  List("apple" , "door", "bank" , "cool")ls.sortWith((x1,x2)=>x1>x2)  //降序val mp = Map[String,Int]("a"->12,"c"->33,"b"->20)val list: List[(String, Int)] = mp.toListlist.sortWith((x1,x2)=>x1._1>x2._1)list.sortWith((x1,x2)=>x1._1<x2._1)list.sortWith((x1,x2)=>x1._2>x2._2)val userMp: Map[String, User] = Map[String, User]("a" -> User("zss", 33), "c" -> User("zss", 23), "b" -> User("lss", 23))userMp.toList.sortWith((u1,u2)=>u1._2.name > u2._2.name)val lp = List((1, "zss", "F", 1200.12), (2, "lss", "F", 2212.12))/*   val users = List[User](User("zss",33),User("zss",23) ,User("lss",23),User("black",20))users.sorted.foreach(println)*/}}
package com._51doit.day03.demo.pojo/*** FileName: User* Author:   多易教育-DOIT* Date:     2020/11/2 0002 * Description: */
case class User(name:String , age:Int) extends Ordered[User] {override def compare(that: User): Int = {if(name.compareTo(that.name)==0){ // 姓名相同-(age - that.age)  // 年龄排序}else{name.compareTo(that.name)  //}}
}

10 flatten

package com._51doit.day03.demo/*** FileName: FlattenDemo* Author:   多易教育-DOIT* Date:     2020/11/2 0002* Description:* 将集合中的每个子集合元素压平*   将子集合中的每个元素取出返回子新的集合中*/
object FlattenDemo {def main(args: Array[String]): Unit = {val arr = Array("hello" ,"tom") // helloval res: Array[Char] = arr.flatten// res.foreach(println)//  val arr2 = Array(11,22,33) //  不能使用val ls:List[Array[String]] = List(Array("hello","tom") , Array("jim","cat"))val res2: List[String] = ls.flattenres2.foreach(println)}}

11 flattenMap

package com._51doit.day03.demoimport java.io.Fileimport scala.collection.mutable
import scala.io.{BufferedSource, Source}/*** FileName: FlattenMapDemo* Author:   多易教育-DOIT* Date:     2020/11/2 0002 * Description: */
object FlattenMapDemo {def main(args: Array[String]): Unit = {val words: Iterator[String] = Source.fromFile(new File("d://word.txt")).getLines().flatMap(_.split("\\s+"))val bs: BufferedSource = Source.fromFile(new File("d://word.txt"))val lines: Iterator[String] = bs.getLines()// flatMap     map line.split("\\s").toList-->  List[Array[String]].flatten//flatMap --->// val words2: Iterator[String] = lines.flatMap(line => line.split("\\s"))val arr = Array("hello tom  jim  cat")// 返回的是 单词  flatten操作的是每个子集合的元素  字符arr.flatten.map(_.toUpper).foreach(println)}}
package com._51doit.day03.demo.test1import java.io.Fileimport scala.io.{BufferedSource, Source}/*** FileName: FlattenTest1* Author:   多易教育-DOIT* Date:     2020/11/2 0002* Description: */
object FlattenTest1 {def main(args: Array[String]): Unit = {//读取文本文件val bs: BufferedSource = Source.fromFile(new File("d://word.txt"))val lines: Iterator[String] = bs.getLines()//获取每行数据-->切割返回数组  多行返回多个数组 存储在迭代器中  Iterator[Array[String]].toList  List[Array[String]]val words: Array[String] = lines.map(_.split("\\s+")).toArray.flattenwords.foreach(println)// 获取每行数据//  lines.foreach(println)// 对行数据切割/*  val res: Iterator[Array[String]] = lines.map(line => {// 处理每行数据val arr: Array[String] = line.split("\\s+")arr})val ls: List[Array[String]] = res.toListval words: List[String] = ls.flattenwords.foreach(println)*//*  /*** [arr* arr* arr* arr]*/res.foreach(println)*/}}

 

  相关解决方案