Scala编程基础3 数组、映射、元组、集合
小白的Scala学习笔记 2024/5/23 14:20
文章目录
- Scala编程基础3 数组、映射、元组、集合
- apply方法
- 数组
- yield
- 数组的一些方法
- 映射
- 元组
- 数据类型转换
- 求和示例
- 拉链
- 集合
- flatMap方法
- Set
- HashMap
apply方法
可以new,也可以不new,不new的时候就调用apply方法
B
class B { def add()={ println("add") } } object B{ //是一个特殊方法,可以认为是构造方法,当没有new的时候,自动调用这个方法 def apply()={ new B() } }
TestB
object TestB { def main(args: Array[String]): Unit = { val b=new B() b.add() val b1=B() b1.add() } }
结果
数组
定长、变长
import scala.collection.mutable.ArrayBuffer object Test14 { def main(args: Array[String]): Unit = { //定长 //为什么不用new? 实现任何都要new,因为有apply方法 val array=Array("a","f","dd") println(array.toBuffer) //变长 val array1 = new ArrayBuffer[String]() array1.append("aa1") array1.append("aa2") array1.append("aa3") array1.append("aa4") println(array1) } }
用ArrayBuffer实现增删改查,主要目的是熟练语法
import java.util.Scanner import scala.collection.mutable.ArrayBuffer object TestArrayBuffer { val scanner = new Scanner(System.in) var array = new ArrayBuffer[String]() def add()={ var addflag=true while (addflag){ println("输入E退出") var input=scanner.nextLine() if(input.equals("E"))addflag=false else array.append(input) } } def delete()={ println("请输入要删除的数据:") var delval=scanner.nextLine() val i = array.indexOf(delval)//找到要删除的值的序号 if(i != -1)array.remove(i) else println("不存在该值") } def update()={ println("请输入要修改的数据:") var updateval=scanner.nextLine() val i = array.indexOf(updateval)//找到要修改的值的序号 if(i != -1){ println("请输入新的值:") array(i)=scanner.nextLine() } else println("不存在该值") } def select()={ for(elm <- array){ println(elm) } } def main(args: Array[String]): Unit = { var isflag=true while (isflag){ println() println("输入“quit”退出系统") println("1.添加 2.删除 3.修改 4.查询") var choiceType = scanner.nextLine() if(choiceType.equals("quit")){ isflag=false } if(choiceType.equals("1"))add() if(choiceType.equals("2"))delete() if(choiceType.equals("3"))update() if(choiceType.equals("4"))select() } } }
yield
对数组中每一个数进行处理
yield关键字将原始的数组进行转换会产生一个新的数组,原始的数组不变
object Test15 { def main(args: Array[String]): Unit = { val array = Array(5,6,7,8,9) val sm=for(elm <- array) yield elm*2 sm.foreach(x => println(x)) println("==============") array.foreach(x => println(x)) } }
数组的一些方法
object Test16 { def main(args: Array[String]): Unit = { val array = Array(3,5,34,62,2) array.foreach(x => println(x))//输出 println("=================") val array2 = array.map(x => x+12)//每个值加12 array2.foreach(x => println(x)) println("=================") val array3 =array.sortBy(x => (-x))//按照-x值排序,结果是降序 array3.foreach(x=>println(x)) println("=================") array.reverse.foreach(x=>println(x))//反转 println("=================") array.sorted.foreach(x=>println(x)) //排序 println("=================") array.sorted.reverse.foreach(x=>println(x))//排序后反转,实现降序 println("=================") println(array.reduce((a, b) => {println(a,b); a+ b}))//全部值求和 } }
object Test18 { def main(args: Array[String]): Unit = { //没有new的话,不能追加,可以更改 val array=Array("zhangsan,lisi","wangwu,zhaoliu") val stringses = array.map(x => x.split(","))//把每个值按”,“分开 for (elm <- stringses) { for (i <- elm){ println(i) } } } }
映射
映射相当于java中的HashMap
不能追加、修改
object Test17 { def main(args: Array[String]): Unit = { //没有new的话是不能追加,也不能修改的 val m=Map("22"->"zhangsan","33"->"lisi") println(m("22"))//取key为22的值 for (elm <- m.keys) { println(elm,m(elm)) } } }
可以追加、修改
package com.oracle.jt import scala.collection.mutable.Map//mutable包下的Map可以追加、修改 object Test19 { def main(args: Array[String]): Unit = { val map=Map[String,String]() map.+=(("22","zhangsan"))//添加值 map.+=(("33","lisi")) map.+=(("44","jjfj")) map("44")="nnnn"//修改 for (elm <- map.keys) { println(elm,map(elm)) } val value1 = map.get("22")//如果输入的key不存在,就会报错 println(value1.get)//返回值是Option val value2 =map.getOrElse("44","default")// 如果输入的key不存在,会输出default,不会报错 println(value2) } }
求单词出现次数
package com.oracle.jt import scala.collection.mutable.Map object Test21 { def main(args: Array[String]): Unit = { val str="hello,tom,jerry,tom,hello" val strings = str.split(",")//分割 //变成(键,1);按键分组,变成(键,(键,1));变成(键,(键,1)取第二列、求和) val res= strings.map(x=>(x,1)).groupBy(x=>x._1).map(x=>(x._1,x._2.map(x=>x._2).sum)) println(res) val tuples: Array[(String, Int)] = strings.map(x => (x, 1))//变成(键,1) val stringToTuples: Predef.Map[String, Array[(String, Int)]] = tuples.groupBy(x => x._1)//按键分组,变成(键,(键,1)) val result: Predef.Map[String, Int] = stringToTuples.map(x => (x._1, x._2.map(x => x._2).sum))//变成(键,(键,1)取第二列、求和) println(result) } }
元组
package com.oracle.jt object TestYuanZu { def main(args: Array[String]): Unit = { val tuple=(2,3,4) println(tuple._1,tuple._2,tuple.x) val tuple2=(2.22,3.33) println(tuple2._2) val tuple3=("zhangsan","lisi") println(tuple3._2) val array=Array("zhangsan",2,44,"lisi",true,2.22) println(array(2)) } }
数据类型转换
直接to
package com.oracle.jt object Test22 { def main(args: Array[String]): Unit = { // 2个元素的元组,可以看成kv对 val list=Array(("22","zhangsan"),("33","lisi")) val map = list.toMap println(map) val s="444" val int = s.toInt println(int) val lng=3333933L; val int1 = lng.toInt println(int1) val float = lng.toFloat println(float) val a="23" val b="34" val sum = a.toInt + b.toInt println(sum) } }
求和示例
package com.oracle.jt import scala.collection.mutable.Map object TestArray2 { def main(args: Array[String]): Unit = { //按 键 求和 val array=Array(("22",12),("33",12),("22",244),("33",19)) val stringToInt = array.groupBy(x => x._1).map(x => (x._1, x._2.map(x => x._2).sum)) println(stringToInt) //也是求和,跟上面一样 val map=Array(("2020-12-12",22),("2020-12-12",88),("2020-12-13",333),("2020-12-13",56)) val stringToInt1 = map.groupBy(x => x._1).map(x => (x._1, x._2.map(x => x._2).sum)) println(stringToInt1) //起始是字符串 val order="2020-12-12,23#2020-12-12,55#2020-12-14,89#2020-12-14,66" val orderArray = order.split("#").map(x => x.split(",")) // for(elm <- orderArray){ // println(elm.toBuffer) // } val tuples: Array[(String, Int)] = orderArray.map(x => (x(0), x(1).toInt))//把Array转换成元组 val stringToInt2 = tuples.groupBy(x => x._1).map(x => (x._1, x._2.map(x => x._2).sum)) println(stringToInt2) // 求每个城市上网的浏览时间 val session="济南,火狐,9#济南,谷歌,15#南宁,谷歌,60" val stringses: Array[Array[String]] = session.split("#").map(x => x.split(",")) val stringToInt3: Predef.Map[String, Int] = stringses.map(x => (x(0), x(2).toInt)).groupBy(x => x._1).map(x => (x._1, x._2.map(x => x._2).sum)) println(stringToInt3) val stringToInt4: Predef.Map[String, Int] = stringses.map(x => (x(1), x(2).toInt)).groupBy(x => x._1).map(x => (x._1, x._2.map(x => x._2).sum)) println(stringToInt4) } }
拉链
两个数组,下标相同的数据合成一个元组,形成一个新的数组
package com.oracle.jt object TestLaLian { def main(args: Array[String]): Unit = { val array1=Array("zhangsan","lisi") val array2=Array("你好","你坏") val tuples: Array[(String, String)] = array1.zip(array2) tuples.foreach(x=>println(x)) } }
集合
Scala的集合有三大类:序列Seq、集Set、映射Map,所有的集合都扩展自Iterable特质
在Scala中集合有可变(mutable)和不可变(immutable)两种类型,immutable类型的集合初始化后就不能改变了(注意与val修饰的变量进行区别)
flatMap方法
object TestList1 { def main(args: Array[String]): Unit = { //拉平,把每个元素分隔开,存到一个新的List中 val list = List("hello,tom","hello,jerry","tom,marry") val strings: List[String] = list.flatMap(x => x.split(",")) strings.foreach(x=>println(x)) //结果:hello,tom,hello,jerry,tom,marry println("+++++++++++++++++") //分割成每个元素后,每个元素变成kv对(元组) val array=List("hello#tom","hello#jerry","tom#marry") val tuples: List[(String, Int)] = array.flatMap(x => x.split("#")).map(x => (x, 1)) tuples.foreach(x=>println(x)) //结果:(hello,1) //(tom,1) //(hello,1) //(jerry,1) //(tom,1) //(marry,1) } }
import scala.collection.mutable.ListBuffer object TestList2 { def main(args: Array[String]): Unit = { val listBuffer = new ListBuffer[String]()//能追加元素 listBuffer.+=("hello jerry") listBuffer.++=(Array("hello marry","tom jerry")) listBuffer.foreach(x=>println(x)) //统计单词出现次数 val tuples: ListBuffer[(String, Int)] = listBuffer.flatMap(x => x.split(" ")).map(x => (x, 1)) val res = tuples.groupBy(x => x._1).map(x => (x._1, x._2.map(x => x._2).sum)) res.foreach(x=>println(x)) } }
Set
object TestSet1 { def main(args: Array[String]): Unit = { val set=Set(1,1,2,90,2)//去重了,所以只有1,2,90 println(set.sum) //93 println("=======================") set.foreach(x=>println(x)) //1 //2 //90 println("=======================") set.map(x=>x*3).foreach(x=>println(x)) //3 //6 //270 println("=======================") println(set.reduce((a, b) => a * b))//累乘的结果 //180 } }
import scala.collection.mutable object TestSet2 { def main(args: Array[String]): Unit = { val set: mutable.HashSet[String] = new mutable.HashSet[String]() set.+=("u01,zhangsan") set.+=("u02,lisi") set.+=("u01,zhangsan") set.foreach(x=>println(x)) val uNumber: mutable.HashSet[String] = set.map(x => x.split(",")).map(x => x(0))//把用户id取出来 println(uNumber.size) println(set.size) println("=================") val ss=new mutable.HashSet[Int]() ss.add(4)//添加元素 ss.+=(9)//添加元素 ss.foreach(x=>println(x)) ss.-=(9)//删除元素 ss.foreach(x=>println(x)) } }
HashMap
import scala.collection.mutable object TestHashMap1 { def main(args: Array[String]): Unit = { val map = new mutable.HashMap[String,Int]() map.+=(("22",1))//添加数据 map.+=(("23",44)) map.put("21",99) map.foreach(x=>println(x)) val ints: mutable.Iterable[Int] = map.map(x => x._2) ints.foreach(x=>println(x)) val tuple: (String, Int) = map.reduce((x, y) => (x._1, x._2 + y._2)) println(tuple) } }
还没有评论,来说两句吧...