集合常用函式
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)
// 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))
/* mp.foreach(tp =>{
tp._1
tp._2
})*/
/* ls.foreach(e=>{
val res: Int = e * 100 + 10
println("hello"+res)
res
})*/
}
}
2 map
package com._51doit.day03.demo
import 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.toUpperCase
val newV: Int = ele._2 * 100
(newK, newV)
})*/
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
/**
* 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)
// 過濾出大于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
/**
* 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的型別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
/**
* 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.demo
import java.io.File
import 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).sum
sum
})
res3.foreach(println)
/* res.map(tp=>{
val word: String = tp._1
val count: Int = tp._2.length
(word ,count)
}).foreach(println)*/
}
}
package com._51doit.day03.demo.test1
import java.io.File
import 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.sort
import 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.sort
import 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.sort
import 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.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))
/* 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") // 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}
/**
* 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.test1
import java.io.File
import 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.flatten
words.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.toList
val words: List[String] = ls.flatten
words.foreach(println)*/
/* /**
* [arr
* arr
* arr
* arr]
*/
res.foreach(println)*/
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/201018.html
標籤:其他
上一篇:MVO優化DBSCAN實作聚類
下一篇:10個冷門的Dcoker技巧
