Scala
- 一、集合
-
- 1、list集合
- 2、map集合
- 3、filter过滤器
- 4、sortBy排序
- 5、SortWith 传入一个比较规则
- 6、flatMap 一行转换为多行
- 7、groupBy指定一个字段进行分组 返回一个Map结构的集合
- 8、set集合 唯一无序
- 9、Tuple元组
- 10、map集合
- 二、WordCountTest
- 三、StudentTest
- 四、ArrayList
- 五、MuTable 可变set 可变map
- 六、Match模式匹配
- 七、Match 模式匹配在map集合上的使用
- 八、隐式转换
- 九、隐式转换类
- 十、ScalaToJava
- 十一、StudentTest 统计总分前十名学生各科的分数
- 十二、偏应用函数
- 十三、函数柯里化
- 十四、反射
-
- 十五、StudentTest
一、集合
1、list集合
object Demo20List {
def main(args: Array[String]): Unit = {
val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
println(list(4))
println(list.head)
println(list.last)
println(list.take(2))
println(list.tail)
println(list.isEmpty)
println(list.reverse)
println(list.distinct)
println(list.mkString(","))
println(list.contains(1))
list.foreach(println)
2、map集合
val list2: List[Int] = list.map((i: Int) => i + 100)
println(list2)
3、filter过滤器
val filterList: List[Int] = list.filter((i: Int) => {
i % 2 == 1
})
println(filterList)
4、sortBy排序
val list3 = List(12, 3, 12, 423, 4, 235, 254, 66, 213, 67, 567, 67, 272)
val sortList: List[Int] = list3.sortBy((i: Int) => -i)
val sortList1: List[Int] = list3.sortBy((i: Int) => i)
println(sortList)
println(sortList1)
5、SortWith 传入一个比较规则
val sortList2: List[Int] = list3.sortWith((i: Int, j: Int) => i > j)
println(sortList2)
println("=" * 100)
val lines: List[String] = List("java,spark,hadoop", "hadoop,spark,hive", "scala,hive,java,hadoop")
for (line <- lines) {
val split: Array[String] = line.split(",")
}
6、flatMap 一行转换为多行
lines.foreach(println)
val words: List[String] = lines.flatMap((line: String) => line.split(","))
words.foreach(println)
7、groupBy指定一个字段进行分组 返回一个Map结构的集合
val list5 = List(1, 2, 4, 6, 7, 3, 1, 2, 3, 4, 5, 6, 7)
val groupBy: Map[Int, List[Int]] = list5.groupBy((i: Int) => i)
groupBy.foreach(println)
}
}
8、set集合 唯一无序
object Demo21Set {
def main(args: Array[String]): Unit = {
val set = Set(1, 2, 2, 1, 2, 2, 3, 4)
println(set)
println(set.mkString(","))
set.foreach(println)
val s1 = Set(1, 3, 4, 5, 6, 2, 4)
val s2 = Set(1, 2, 7, 9, 3, 6, 9, 1)
println(s1 & s2)
println(s1 | s2)
println(s1 &~ s2)
}
}
9、Tuple元组
object Demo22Tuple {
def main(args: Array[String]): Unit = {
val t = (1,2,3,4,5,6,10)
println(t._1)
val array: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7)
println(array(6))
}
}
10、map集合
object Demo23Map {
def main(args: Array[String]): Unit = {
val map: Map[String, String] = Map(("001", "张三"), ("002", "李四"), ("003", "王五"), "004" -> "赵六")
println(map)
println(map("004"))
println(map.getOrElse("007","默认值"))
}
}
二、WordCountTest
import scala.io.Source
object Demo24WordCount {
def main(args: Array[String]): Unit = {
val lines: List[String] = Source.fromFile("data/words.txt")
.getLines()
.toList
val words: List[String] = lines.flatMap((line: String) => line.split(","))
val groupBy: Map[String, List[String]] = words.groupBy(word => word)
val wordCount: Map[String,Int] = groupBy.map((kv: (String, List[String])) => {
val word: String = kv._1
val values: List[String] = kv._2
val count : Int = values.length
(word,count)
})
wordCount.foreach(println)
Source
.fromFile("data/words.txt")
.getLines()
.toList
.flatMap(line=>line.split(","))
.groupBy(word=>word)
.map(kv=>(kv._1,kv._2.length))
.foreach(println)
}
}
三、StudentTest
import scala.io.Source
object Demo25Student {
def main(args: Array[String]): Unit = {
val students: List[String] = Source.fromFile("data/students.txt").getLines().toList
val clazzs: List[String] = students.map(student => {
val split: Array[String] = student.split(",")
split(4)
})
val groupBy: Map[String, List[String]] = clazzs.groupBy(clazz => clazz)
val clazzCount: Map[String, Int] = groupBy.map((kv: (String, List[String])) => {
val clazz: String = kv._1
val values: List[String] = kv._2
val count: Int = values.length
(clazz, count)
})
clazzCount.foreach(println)
println("=" * 100)
val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList
val kvScore: List[(String, Int)] = scores.map(score => {
val split: Array[String] = score.split(",")
val id: String = split(0)
val sco: Int = split(2).toInt
(id, sco)
})
val groupByScore: Map[String, List[(String, Int)]] = kvScore.groupBy(kv => kv._1)
val groupBySumScore: Map[String, Int] = groupByScore.map((kv: (String, List[(String, Int)])) => {
val id: String = kv._1
val scos: List[(String, Int)] = kv._2
val ints: List[Int] = scos.map(i => i._2)
val sumScore: Int = ints.sum
(id, sumScore)
})
groupBySumScore.foreach(println)
}
}
四、ArrayList
import java.util
object Demo26ArrayList {
def main(args: Array[String]): Unit = {
val list = new util.ArrayList[String]
list.add("java")
list.add("scala")
list.add("hadoop")
list.add("hbase")
list.add("hive")
println(list)
var i = 0
while (i < list.size()){
println(list.get(i))
i+=1
}
}
}
五、MuTable 可变set 可变map
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
object Demo27MuTable {
def main(args: Array[String]): Unit = {
val listBuffer = new ListBuffer[String]
listBuffer += ("java")
listBuffer += "spark"
listBuffer += "spark"
listBuffer ++= List("1", "2", "3")
println(listBuffer)
listBuffer(0) = "hadoop"
println(listBuffer)
listBuffer -= "spark"
listBuffer --= List("1", "2")
println(listBuffer)
val hashMap = new mutable.HashMap[String, String]()
hashMap.put("001", "张三")
hashMap.+=(("002", "李四"))
hashMap += "003" -> "王五"
println(hashMap)
hashMap.remove("001")
hashMap -= "002"
hashMap += "003" -> "王五1"
println(hashMap)
val hashSet = new mutable.HashSet[String]()
hashSet.add("java")
hashSet += "hadoop"
hashSet += "hadoop"
hashSet += "spark"
hashSet ++= List("1", "2", "3")
println(hashSet)
hashSet.remove("java")
hashSet -= "hadoop"
println(hashSet)
}
}
六、Match模式匹配
import scala.io.Source
object Demo28Match {
def main(args: Array[String]): Unit = {
val i = 300
i match {
case 100 => println("i等于100")
case 200 => println("i等于200")
case _ => println("其它")
}
val s = "java"
s match {
case "java" => println("s等于java")
case "hadoop" => println("s等于hadoop")
case _ => println("其它")
}
case class User(id: String, name: String)
val user = User("001", "张三")
user match {
case User("001", "张三") => println("张三")
case User("002", "李四") => println("李四")
case _ => println("其它")
}
val obj: Any = List("java", "hadoop")
obj match {
case s: String => println(s"obj是一个字符串:$s")
case i: Int => println(s"obj是一个Int类型:$i")
case list: List[String] => println(s"obj是一个集合:$list")
case _ => println("其他类型")
}
val j = 101
val str: String = j % 2 match {
case 1 => "奇数"
case 0 => "偶数"
}
println(str)
val list: List[(String, String, Int)] = List(("001", "张三", 23), ("002", "李四", 24), ("003", "王五", 25))
val result: List[(String, String, Int)] = list.map((kv: (String, String, Int)) => {
val id: String = kv._1
val name: String = kv._2
val age: Int = kv._3
(id, name, age + 1)
})
result.foreach(println)
println("=" * 100)
list
.map {
case (id: String, name: String, age: Int) =>
(id, name, age + 1)
}
.foreach(println)
val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList
val kvScore: List[(String, Int)] = scores.map(score => {
val split: Array[String] = score.split(",")
val id: String = split(0)
val sco: Int = split(2).toInt
(id, sco)
})
val groupByScore: Map[String, List[(String, Int)]] = kvScore.groupBy(kv => kv._1)
groupByScore
.map {
case (id: String, scos: List[(String, Int)]) =>
val scoress: List[Int] = scos.map {
case (i: String, sco: Int) => sco
}
val sumScore: Any = scoress.sum
(id, sumScore)
}
.foreach(println)
println("="*100+"匹配数组")
scores
.map(line => line.split(","))
.map {
case Array(id: String, _: String, sco: String) =>
(id, sco.toInt)
}
.foreach(println)
}
}
七、Match 模式匹配在map集合上的使用
bject Demo29Match {
def main(args: Array[String]): Unit = {
val map = Map("001" -> "张三", "002" -> "李四")
println(map.getOrElse("003","默认值"))
println(map("001"))
val option: Option[String] = map.get("001")
println(option.get)
val value: String = map.get("001") match {
case Some(v) => v
case None => "默认值"
}
println(value)
}
}
八、隐式转换
object Demo30Implicit {
def main(args: Array[String]): Unit = {
val s: String = "1000"
val i: Int = s.toInt
def fun(str: String) : Unit ={
println("fun:"+str)
}
fun("java")
fun(100.toString)
implicit def intToString(i: Int): String ={
println("intToString")
i.toString
}
implicit def doubleToString(d: Double): String ={
d.toString
}
fun(1000)
fun(3.14)
val ii: Int = "100".toInt
}
}
九、隐式转换类
import scala.io.Source
object Demo31Implicit {
def main(args: Array[String]): Unit = {
val path = "data/students.txt"
val stus: List[String] = path.load
println(stus)
val scores: List[String] = "data/score.txt".load
println(scores)
}
implicit class Read(path: String){
def load: List[String] = {
println("读取数据的方法")
Source.fromFile(path).getLines().toList
}
}
}
十、ScalaToJava
import java.util
object Demo32ScalaToJava {
def main(args: Array[String]): Unit = {
val arrayList = new util.ArrayList[String]
arrayList.add("a")
arrayList.add("b")
arrayList.add("c")
arrayList.add("d")
import scala.collection.JavaConversions._
val list: List[String] = arrayList.toList
println(list)
import scala.collection.JavaConverters._
val javaList: util.List[String] = list.asJava
println(javaList)
}
}
十一、StudentTest 统计总分前十名学生各科的分数
import scala.io.Source
object Demo33Student {
def main(args: Array[String]): Unit = {
val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList
val kvScores: List[(String, String, Int)] = scores
.map(line => line.split(","))
.filter(arr => arr.length == 3)
.map {
case Array(id: String, cId: String, sco: String) =>
(id, cId, sco.toInt)
}
val groupBySco: Map[String, List[(String, String, Int)]] = kvScores.groupBy {
case (id: String, _: String, _: Int) => id
}
val sumSco: Map[String, Int] = groupBySco.map {
case (id: String, scos: List[(String, String, Int)]) =>
val sumSco: Int = scos
.map {
case (_: String, _: String, sco: Int) => sco
}
.sum
(id, sumSco)
}
val sumScoreList: List[(String, Int)] = sumSco.toList
val sortSumScore: List[(String, Int)] = sumScoreList.sortBy {
case (_: String, sumSco: Int) => -sumSco
}
val top10: List[(String, Int)] = sortSumScore.take(10)
val ids: List[Any] = top10.map(kv => kv._1)
val top10Scores: List[(String, String, Int)] = kvScores.filter {
case (id: String, _: String, _: Int) =>
ids.contains(id)
}
top10Scores.foreach(println)
}
}
package com.shujia.scala
import scala.io.Source
object Demo33Student2 {
def main(args: Array[String]): Unit = {
val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList
val kvScores: List[(String, String, Int)] = scores
.map(line => line.split(","))
.filter(arr => arr.length == 3)
.map {
case Array(id: String, cId: String, sco: String) =>
(id, cId, sco.toInt)
}
kvScores.foreach(println)
}
}
十二、偏应用函数
package com.shujia.scala
object Demo34Fun {
def main(args: Array[String]): Unit = {
def fun(x: Int,y:Int): Int= x * y
println(fun(100,200))
val f: Int => Int = fun(100, _: Int)
println(f(200))
println(f(300))
println(f(400))
println(fun(100,200))
println(fun(100,300))
println(fun(100,400))
}
}
十三、函数柯里化
package com.shujia.scala
import scala.io.{BufferedSource, Codec, Source}
object Demo35Fun {
def main(args: Array[String]): Unit = {
def fun(x: Int)(y: Int): Int = {
x * y
}
val i: Int = fun(100)(200)
println(i)
val f: Int => Int = fun(100)
println(f(100))
println(f(200))
println(f(300))
implicit val num: Int = 100
def fun2(x: Int)(implicit y: Int): Int = x * y
println(fun2(2)(3))
println(fun2(2))
val source: BufferedSource = Source
.fromFile("data/students.txt")(Codec("utf-8"))
println(source)
}
}
十四、反射
1、反射
package com.shujia.scala
object Demo36Class {
def main(args: Array[String]): Unit = {
val clazz: Class[_] = Class.forName("java.util.ArrayList")
val clazz1: Class[String] = classOf[String]
val str: String = "java"
val clazz2: Class[_ <: String] = str.getClass
}
}
2、通过反射绕过泛型对类型的限制
package com.shujia.scala;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class Demo37 {
public static void main(String[] args) throws Exception{
ArrayList<String> list = new ArrayList<>();
list.add("java");
list.add("hadoop");
list.add("spark");
System.out.println(list);
Class<? extends ArrayList> listClass = list.getClass();
Method add = listClass.getMethod("add", Object.class);
add.invoke(list,100);
System.out.println(list);
}
}
十五、StudentTest
package com.shujia.scala
import scala.io. Source
object DemoTest {
def main(args: Array[String]): Unit = {
val students: List[String] = Source.fromFile("data/students.txt")
.getLines()
.toList
val students_map: Map[String, List[String]] = students.groupBy(student => student.split(",")(4))
students_map.foreach(println)
val students_clazz: Map[String, Int] = students_map.map((f: (String, List[String])) => {
val value: String = f._1
val length: Int = f._2.length
(value,length)
})
students_clazz.foreach(println)
}
}