SCALA-DAY03(课堂代码)

   日期:2020-11-03     浏览:95    评论:0    
核心提示:集合常用函数1 forEachpackage com._51doit.day03.demo.

集合常用函数

1 forEach 

package com._51doit.day03.demo


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)
    // list
    ls.foreach(e=>println(e))
    ls.foreach(e=>println(e*10))
    ls.foreach(println(_))
    ls.foreach(println)
    ls.foreach(e=>print(e+" "))
    // 映射集合  Map
    mp.foreach(tp=>println(tp))
    mp.foreach(tp=>println(tp._1))
    mp.foreach(tp=>println(tp._2))


   


   

  }

}

2 map

package com._51doit.day03.demo

import scala.collection.immutable


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
    

    mp.map(ele => {
      val newK: String = ele._1.toUpperCase
      val newV: Int = ele._2 * 100
      (newK, newV)
    }).foreach(println)
    //处理每个元素 返回的数据结构没有变化
    mp.map(e => {
      (e._1.toUpperCase, e._2 * 100)
    })
    // 返回的数据结构  只返回v
    val 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


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)
    // 过滤出大于5
    val res1: List[Int] = ls.filter(e => e > 5)
    // 偶数
    ls.filter(_%2==0)
    //多条件过滤   &&
    ls.filter(e=> e%2==0 && e>5)
    // 多条件的  多次调用filter
    ls.filter(_%2==0).filter(_>5).foreach(println)
   // array
    val 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


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


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


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的类型true
        x.isInstanceOf[Int]
      }
    // 上面方法返回true的时候 指定这个方法
      override def apply(v1: Any): Int = { // 1 2 3 4 5 6 7
        v1.asInstanceOf[Int] *10
      }
    }
    // 遍历每个元素  ->1 (isDefinedAt)-->(apply)--10 -->新的集合中
   ls.collect(pf).foreach(println)
   // ls.map(pf).foreach(println)
  }
}

5 mapValues

package com._51doit.day03.demo


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.demo

import java.io.File

import scala.io.{BufferedSource, Source}


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).sum
      sum
    })
    res3.foreach(println)
   

  }

}
package com._51doit.day03.demo.test1

import java.io.File

import scala.io.Source


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.sort

import com._51doit.day03.demo.pojo.User


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.sort

import com._51doit.day03.demo.pojo.User


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)

 


  }

}

9sortWith

package com._51doit.day03.demo.sort

import com._51doit.day03.demo.pojo.User


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.toList
    list.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))

 


  }

}
package com._51doit.day03.demo.pojo


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


object FlattenDemo {
  def main(args: Array[String]): Unit = {
    val arr = Array("hello" ,"tom") // hello
    val 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.flatten
    res2.foreach(println)

  }

}

11 flattenMap

package com._51doit.day03.demo

import java.io.File

import scala.collection.mutable
import scala.io.{BufferedSource, Source}


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.test1

import java.io.File

import scala.io.{BufferedSource, Source}


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.flatten
    words.foreach(println)

    // 获取每行数据
    //  lines.foreach(println)
    // 对行数据切割
    


    
      res.foreach(println)*/


  }

}

 

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服