和java一样
var name : String = "jx" // 变量
val name : String = "jx" // 常量
因为scala函数式编程的要素,所以能用常量就不要用变量
var _asd : String = "jx"
val +-*/ = "jx"
val `jx` = "jx"
val name : String = "j" + " " + "x"
val age : Integer = 20
println((name + " ") * 3)
printf("%s", name)
println()
print(s"name $name $age ")
println(f"name $age")
val sql = s"""
|select *
|from
|student
|where
|name = $name
"""
println(sql)
输出:
j x j x j x
j x
name j x 20 name 20
|select *
|from
|student
|where
|name = j x
import java.io.{File, PrintWriter}
import scala.io.Source
object test {
def main(args: Array[String]): Unit = {
// read from file
Source.fromFile("hello.txt").foreach(print)
// write to file
// call java API to write
val writer = new PrintWriter(new File("hello.txt"))
writer.write("jx")
writer.close()
}
}
Scala中运算符就是方法。10.+(1)即是10 + 1
if-else
for循环:
for (i <- collection if condition) {
}
等价于
for (i <- collection) {
if (condition) {
}
}
for (i <- 1 to 4) {
for (j <- 1 to 5) {
println()
}
}
等价于
for (i <- 1 to 4; j <- 1 to 5) {
println()
}
import scala.util.control.Breaks
Breaks.breakable {
for (i <- 0 to 10) {
if (i == 3) {
Breaks.break()
}
}
}
def fun(str : String*) : Unit = {}
def fun(name : String = "jx") : Unit = {}
def fun(name : String, age : Int = 20, loc : String = "hlj") : Unit = {
}
fun("jx")
fun("jx", age = 21)
fun("jx", loc = "gx")
val fun = (name : String) => {println()}
def fun(func : String => Unit) : Unit = {
func("jx")
}
fun((name : String) => {println(name)})
fun((name : String) => println(name))
fun((name) => println(name))
fun(println(_))
fun(println)
def fun(func : (Int, Int) => Int) : Int = {
fun(1, 2)
}
val add = (a : Int, b : Int) => a + b
val minus = (a : Int, b : Int) => a + b
println(func(add))
println(func(add))
// 可以简化为
val add = (_ + _)
val minus = (-_ + _)
def f(n : Int): Int = {
println("f")
n + 1
}
def fun() : Int = {
1
}
// 函数作为值传递
val f1 : Int => Int = f // 指出了最终的类型,所以知道了f是一个函数
val f2 = f _ // f _ 代表是一个函数
val f3 = fun // fun代表的是返回值,即1,因为没有传入值,所以可以之间调用
val f4 = fun _ // 代表一个函数
// 函数作为参数进行传递
// 定义二元运算函数
def sum(op : (Int, Int) => Int, a : Int, b : Int) : Int {
op(a + b)
}
def add(a : Int, b: Int) : Int {
a + b
}
println(sum(add, 12, 22))
// 函数作为函数返回值返回
def f5() : Int => Unit = {
def f6(a : Int) : Unit = {
println("f6")
}
f6 // 当函数直接返回
}
println(f5()(22)) // f5()得到的是f6
var arr : Array[Int] = Array(1, 24, 12, 11)
// 对数组进行梳理,将操作抽象出来,处理完毕之后将结果返回一个新的数组
def arrayOperation(array : Array[Int], op : Int => Int) : Array[Int] = {
// yield : 生成一个新的数组
for (elem <- array) yield op(elem)
}
// 定义加一操作
def addOne(elem : Int) : Int = {
elem + 1
}
// 调用函数
val newArray : Array[Int] = arrayOperation(arr, addOne)
// 直接传入匿名函数,进行乘2操作
val newArray2 : Array[Int] = arrayOperation(arr, _*2)
println(newArray2.mkString(","))
// 结果:2,48,24,22
println(newArray.mkString(","))
// 结果:2,25,13,12
闭包:函数式编程标配。如果一个函数,访问到他的外部(局部)变量的值,那么这个函数和他所处的环境,称为闭包
def func(i : Int) : String => (char => Boolean) = {
def f1(s : String) : Char => Boolean = {
def f2 (c : Char) ; Boolean = {
if (i == 0 && s == " " && c == '0') false else true
}
f2
}
f1
}
def add(a : Int, b : Int) : Int = {
a + b
}
// 考虑固定一个加数的场景内
def addByFour(b : Int) : Int = {
4 + b
}
// 扩展固定家属改变的情况
def addByFive(b : Int) : Int = {
5 + b
}
// 将固定加数作为另一个参数传入,但是是作为第一层参数传入
def addByFour1() : Int => Int = {
val a = 4
def addB(b : Int) {
a + b
}
addB
}
def addByA(a : Int) : Int => Int = {
def addB(b : Int) : Int = {
a + b
}
addB
}
// addByA可以简化为
def addByA(a : Int) : Int => Int = a + _
println(addByA(35)(23))
函数柯里化:把一个参数列表的多个参数,变成多个参数的列表
// 底层是闭包
def addCurrying(a : Int)(b : Int) : Int = {
a + b
}
scala中递归定义函数必须声明返回值类型,因为无法通过推导获得
// 按值传递
def f0(a: Int): Unit = {
println("a: " + a)
println("a: " + a)
}
f0(10)
// 按名传递,传递的不再是具体值,而是代码块
def f1(a: => Int): Unit = {
println("a: " + a)
println("a: " + a)
}
def f2(): Int = {
println("call f2()")
10
}
f1(10)
f1(f2()) // 将代码块完整的调用过去
f1({
println("code block")
30
})
lazy
时,函数的执行将会被推迟,直到我们首次对此取值,该函数才会被执行。这种函数成为惰性函数def main(args: Array[String]): Unit = {
lazy val result: Int = sum(13, 47)
println("函数调用")
println(s"result = ${result}")
}
def sum(a: Int, b: Int): Int = {
println("sum 调用")
a + b
}
// 结果为:
//函数调用
//sum 调用
//result = 60
scala有两种包管理风格,一种和java相同,另一种风格,通过嵌套表示层级关系
package com {
package jx {
package scala {
}
}
}
第二种风格有以下特点
package com {
import com.atguigu.Inner //父包访问子包需要导包
object Outer {
val out: String = "out"
def main(args: Array[String]): Unit = {
println(Inner.in)
}
}
package atguigu {
object Inner {
val in: String = "in"
def main(args: Array[String]): Unit = {
println(Outer.out) //子包访问父包无需导包
}
}
}
}
package object inner {
}
回顾java的类:一般一个类中只能有一个public类,如果类是public的,必须和文件名一致
scala中没有public,默认就是public,一个scala中可以写多个类
Bean属性:@BeanPropetry,可以自动生成getter,setter方法
class Person {
var name : String = "jx" // 定义属性
var age : Int = _ // _表示给属性一个默认值
// Bean属性
@BeanProperty var sex : String = "boy"
// val修饰的属性不能赋默认值,必须显示指定
}
object Person {
def main (args : Array[String]) : Unit = {
var person = new Person()
person.setSex("girl")
}
}
def 方法体(参数列表) : 返回值类型 = {
}
scala的构造器分为主构造器和辅助构造器
class 类名(形参列表) { // 主构造器
def this(形参列表) { // 辅助构造器
}
def this(形参列表) { // 辅助构造器可以有多个
}
}
class Person {
var name : String = _
var age : Int = _
def this(age : Int) {
this()
this.age = age
}
def this(age : Int, name : String) {
this(age)
}
}
object Person {
def main(args : Array[String]) : Unit = {
val Person2 = new Person(10)
}
}
class Person {
val name : String = "Person"
def hello() : Unit = {
println("hello Person")
}
}
class Teacher extends Person {
override val name : String = "teacher"
override def hello() : Unit = {
println("hello teacher")
}
}
object Test {
def main(args : Array[String]) : Unit = {
val teacher : teacher = new Teacher()
println(teacher.name)
teacher.hello()
val teacher1 : Person = new Teacher
println(teacher1.name)
teacher1.hello()
}
}
//输出结果 :
// teacher
// hello teacher
// teacher
// hello teacher
// 相同的代码,java的输出结果:
// teacher
// hello teacher
// Person
// hello teacher
object Person {
var name : String = "jx"
}
class person {
var name : String = "zx"
}
object Test {
def main(args : Array[String]) : Unit = {
println(Person.name)
}
}
// 动态混入
val t = new Teacher with Trait {
}
当引入的多个trait中有相同的方法,会出现继承冲突问题
// 特质叠加策略
trait Ball {
def describe(): String = {
"ball"
}
}
trait Color extends Ball {
override def describe(): String = {
"blue-" + super.describe()
}
}
trait Category extends Ball {
override def describe(): String = {
"foot-" + super.describe()
}
}
class MyBall extends Category with Color {
override def describe(): String = {
"my ball is a " + super.describe()
}
object TestTrait {
def main(args: Array[String]): Unit = {
println(new MyBall().describe())
}
}
// 运行结果:my ball is a blue-foot-ball
当一个类中混入多个特质时,scala会对所有的特质及其父特质按照一定的顺序排序,排序的规则如下:
class User(val name: String, val age: Int)
trait Dao {
def insert(user: User) = {
println("insert into database :" + user.name)
}
}
trait APP {
// 可以表示当前特质里有一个Dao
_: Dao =>
def login(user: User): Unit = {
println("login :" + user.name)
insert(user)
}
}
object MyApp extends APP with Dao {
def main(args: Array[String]): Unit = {
login(new User("bobo", 11))
}
使用type关键字可以定义新的数据类型
List归属Seq,和java中的概念不同
for循环的 1 to 3 就是IndexSeq的Range
scala中的Map体系中有一个SortedMap,说明scala的Map支持排序
IndexedSeq和LinearSeq的区别:
IndexedSeq是通过索引来查找和定位,速度快
LinearSeq是线型的,有头和尾的概念,一般通过遍历查找
val arr = new Array[Int] (10)
new是关键字
[Int]指定存放的数据类型,如果希望存放任意数据,指定Any
(10)表示数组大小,确定后不能变化
val arr = new Array(1,2)
定义数组,直接赋初值
使用apply方法创建数组对象
object Test {
def main(args : Array[String]) : Unit = {
// 创建一个List(数据有顺序,可重复)
val list : List[Int] = List(1,2,3,4,3)
println(list) // List(1, 2, 3, 4, 3)
list.foreach(println) // 12343
println(list(1)) // 2
// list(1) = 12 不能操作
// 添加元素
var list2 = list.+:(10) // 开头加
var list3 = list.:+(10) // 结尾加
println(list)
println(list2)
println(list3)
// 输出结果
//List(1, 2, 3, 4, 3)
//List(10, 1, 2, 3, 4, 3)
//List(1, 2, 3, 4, 3, 10)
val list4 = list.::(123)
println(list4) // List(123, 1, 2, 3, 4, 3)
val list5 = Nil.::(13)
println(list5) // List(13)
val list6 = 17 :: 28 :: 59 :: 16 :: Nil
println(list6) // List(17, 28, 59, 16)
val list7 = list6 :: list5
println(list7) // List(List(17, 28, 59, 16), 13)
// 扁平化:整体拆成个体,然后整合成一个list
val list8 = list5 ::: list6
println(list8) //List(13, 17, 28, 59, 16)
val list9 = list5 ++ list6
println(list9) // List(13, 17, 28, 59, 16)
}
}
object Test {
def main(args : Array[String]) : Unit = {
// 创建一个可变的集合
val buffer = ListBuffer(1, 2, 3, 4)
// 向集合中添加元素
buffer.+=(5)
buffer.append(6)
buffer.insert(1, 2)
// 打印数据
buffer.foreach(print) // 1223456
println()
// 修改数据
buffer(1) = 6
buffer.update(1, 7)
buffer.foreach(print) //1723456
println()
// 删除数据
buffer.-(5)
buffer.-=(1)
buffer.remove(2)
buffer.foreach(print) //72456
}
}
默认情况下,Scala使用的是不可变集合,如果想使用可变集合,需要引用scala.collection.mutable.Set包
object Test {
def main(args : Array[String]) : Unit = {
// Set默认是不可变集合,数据无序
val set = Set(1, 2, 3, 4, 5, 6)
// 数据不可重复
val set1 = Set(1, 2, 3, 4, 5 ,6, 3)
// 遍历集合
for (x <- set1) {
println(x) // 516234
}
}
}
object Test {
def main(args : Array[String]) : Unit = {
// 创建可变集合
val set = mutable.Set(1, 2, 3, 4, 5)
// 添加元素
set += 8
// 向集合中添加元素,返回一个新的Set
val set1 = set.+(9)
println(set1) // Set(9, 1, 5, 2, 3, 4, 8)
println(set) //Set(1, 5, 2, 3, 4, 8)
// 删除数据】
set -= (5)
// 遍历
set.foreach(print) // 12348
println(set.mkString(",")) //1,2,3,4,8
}
}
散列表,存储的内容是键值对
object Test {
def main(args : Array[String]) : Unit = {
// 创建不可变集合
val map = Map("a" -> 1, "b" -> 2)
// 访问数据
for (elem <- map.keys) {
// 使用get访问map的数据,返回特殊类型Option(选项),Some(有值),None(无值)
print(elem + "=" + map.get(elem).get) // a=1b=2
}
// 如果key不存在,返回0
println(map.get("d").getOrElse(0)) // 0
println(map.getOrElse("b", 0)) // 2
// 遍历
map.foreach((kv) => {println(kv)})
//(a,1)
//(b,2)
}
}
object Test {
def main(args : Array[String]) : Unit = {
// 创建可变集合
val map = mutable.Map("a" -> 1, "b" -> 2)
// 添加数据
map .+= ("c" -> 3)
// 将4添加到集合,把结合中的原值1返回
val maybeInt = map.put("a", 4)
println(maybeInt.getOrElse(0)) //1
// 删除数据
map .-=("b")
// 修改数据
map.update("d", 5)
map("d") = 5
// 遍历
map.foreach((kv) => {println(kv)})
}
}
object Test {
def main(args : Array[String]) : Unit = {
// 声明元组
val tuple : (Int, String, Boolean) = (20, "jx", true)
// 通过元素的顺序进行访问, _顺序号
println(tuple._1)
println(tuple._2)
println(tuple._3)
// 通过索引访问数据
println(tuple.productElement(0))
// 通过迭代器来访问数据
for (elem <- tuple.productIterator) {
println(elem)
}
// Map中的键值对就是元组,不过元组的元素个数为2,称之为对偶
val map = Map("a" -> 1, "b" -> 2)
val map1 = Map(("a", 1), ("b", 2))
map.foreach(tuple => {println(tuple._1 + "=" + tuple._2)})
map1.foreach(tuple => {println(tuple._1 + "=" + tuple._2)})
/*
* 输出结果:
* 20
jx
true
20
20
jx
true
a=1
b=2
a=1
b=2
* */
}
}
object Test {
def main(args : Array[String]) : Unit = {
var list : List[Int] = List(1, 2, 3, 4, 5, 6)
// 获取数组长度
println(list.length)
// 获取集合大小(等同于length)
println(list.size)
// 循环遍历
list.foreach(println)
// 迭代器
for(elem <- list.iterator) {
println(elem)
}
// 生成字符串
println(list.mkString(","))
// 是否包含
println(list.contain(0))
}
}
object Test {
def main(args : Array[String]) : Unit = {
var list1 : List[Int] = List(1, 2, 3, 4, 5, 6)
var list2 : List[Int] = List(7, 8, 9, 0, 10, 11)
// 获取集合的头
println(list1.head)
// 获取集合的尾(除了头都是尾)
println(list1.tail)
// 集合中的最后一个元素
println(list1.last)
// 集合初始元素(不包含最后一个元素)
println(list1.init)
// 反转
println(list1.reverse)
// 取前(后)n个元素
println(list1.take(3))
println(list1.takeRight(3))
// 去掉前(后)n个元素
println(list1.drop(3))
println(list1.dropRight(3))
// 并集
println(list1.union(list2))
// 交集
println(list1.intersect(list2))
// 差集
println(list1.diff(list2))
// 拉链
// 如果两个集合的元素个数不同,那么会将同等数量的数据进行拉链
println(list1.zip(list2))
// 滑窗
// 2: 窗口大小
// 5: 滑动距离
list1.sliding(2, 5).foreach(println)
/*
* 1
List(2, 3, 4, 5, 6)
6
List(1, 2, 3, 4, 5)
List(6, 5, 4, 3, 2, 1)
List(1, 2, 3)
List(4, 5, 6)
List(4, 5, 6)
List(1, 2, 3)
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 10, 11)
List()
List(1, 2, 3, 4, 5, 6)
List((1,7), (2,8), (3,9), (4,0), (5,10), (6,11))
List(1, 2)
List(6)
* */
}
}
object test {
def mian(args : Array[String]) : Unit = {
var list : List[Int] = List(1, 2, 3, 4, 5, 6)
// 求和
println(list.sum)
// 求乘积
println(list.product)
// 最大值
println(list.max)
// 最小值
println(list.min)
// 排序
// 按照元素大小
println(list.sortBy(x => x))
// 按照元素绝对值大小排序
println(list.sortBy(x => x.abs))
// 按照元素大小升序排序
println(list.sortWith((x, y) => x < y))
// 按照元素大小降序排列
println(list.sortWith((x, y) => x > y))
/*
* 21
720
6
1
List(1, 2, 3, 4, 5, 6)
List(1, 2, 3, 4, 5, 6)
List(1, 2, 3, 4, 5, 6)
List(6, 5, 4, 3, 2, 1)
*
* */
}
}
object test {
def main(args: Array[String]): Unit = {
val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
// 过滤
//选取偶数
val evenList = list.filter((elem : Int) => {elem % 2 == 0})
println(evenList)
println(list.filter(_ % 2 == 1))
println("===============")
// map
// 把集合中每个数*2
println(list.map(_ * 2))
// println(list.map(_ * _)) ×
println(list.map(x => x * x))
println("===========")
// 扁平化
val nestedList : List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
// val flatList = nestedList(0) ::: nestedList(1) ::: nestedList(2)
// println(flatList)
println(nestedList)
val flatList = nestedList.flatten
println(flatList)
println("==========")
// 扁平映射
// 将一组字符串进行分词,并保存成单词的列表
val strings : List[String] = List("hello world", "hello scala", "hello spark")
val splitList : List[Array[String]] = strings.map(_.split(" "))
println(splitList)
val flattenList = splitList.flatten // 打散扁平化
println(flattenList)
println("===========")
val flatmapList = strings.flatMap(_.split(" "))
println(flatmapList)
println("=============")
// 分组groupBy
// 分成奇偶两组
val groupMap : Map[Int, List[Int]] = list.groupBy(_ % 2)
println(groupMap)
val groupMap2 : Map[String, List[Int]] = list.groupBy(data => {
if (data % 2 == 0) "偶数" else "奇数"
})
println(groupMap2)
// 给定一组词汇,按照单词的首字母进行分组
val wordList = List("China", "Americ", "asd", "fgh", "jkl")
println(wordList.groupBy(_.charAt(0)))
}
}
/*
* 输出结果:
* List(2, 4, 6, 8)
List(1, 3, 5, 7, 9)
===============
List(2, 4, 6, 8, 10, 12, 14, 16, 18)
List(1, 4, 9, 16, 25, 36, 49, 64, 81)
===========
List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
List(1, 2, 3, 4, 5, 6, 7, 8, 9)
==========
List([Ljava.lang.String;@3532ec19, [Ljava.lang.String;@68c4039c, [Ljava.lang.String;@ae45eb6)
List(hello, world, hello, scala, hello, spark)
===========
List(hello, world, hello, scala, hello, spark)
=============
Map(1 -> List(1, 3, 5, 7, 9), 0 -> List(2, 4, 6, 8))
Map(奇数 -> List(1, 3, 5, 7, 9), 偶数 -> List(2, 4, 6, 8))
Map(j -> List(jkl), f -> List(fgh), A -> List(Americ), a -> List(asd), C -> List(China))
*
* */
object test1 {
def main(args: Array[String]): Unit = {
val list = List(1, 2, 3, 4)
// reduce
// list.reduce((a : Int, b : Int) => a + b)
println(list.reduce(_ + _))
println(list.reduceLeft(_ + _))
println(list.reduceRight(_ + _))
println("================")
val list2 = List(3, 4, 5, 8, 10)
println(list2.reduce(_ - _))
println(list2.reduceLeft(_ - _))
println(list2.reduceRight(_ - _)) // 3 - (4 - (5 - (8 - 10)))
}
}
/*
* 输出结果
* 10
10
10
================
-24
-24
6
* */
object test1 {
def main(args: Array[String]): Unit = {
val list = List(1, 2, 3, 4)
// fold
println(list.fold(10)(_ + _)) // 10 + 1 + 2 + 3 + 4
println(list.foldLeft(10)(_ - _))
println(list.foldRight(10)(_ - _)) // 1 - (2 - (3 - (4 - 10)))
}
}
/*
* 输出结果
* 20
* 0
* 8
* */
object test1 {
def main(args: Array[String]): Unit = {
val map1 = Map("a" -> 1, "b" -> 3, "c" -> 6)
val map2 = mutable.Map("a" -> 2, "b" -> 4, "c" -> 5)
println(map1 ++ map2)
println(map2 ++ map1)
val stringToInt = map1.foldLeft(map2)(
(mergedMap, kv) => {
val key = kv._1
val value = kv._2
mergedMap(key) = mergedMap.getOrElse(key, 0) + value
mergedMap
}
)
println(stringToInt)
}
/*
* 输出结果
* Map(a -> 2, b -> 4, c -> 5)
Map(b -> 3, a -> 1, c -> 6)
Map(b -> 7, a -> 3, c -> 11)
* */
}
object test1 {
def main(args: Array[String]): Unit = {
val stringList : List[String] = List (
"hello",
"hello world",
"hello scala",
"hello spark from scala",
"hello fink from scala"
)
// 对字符串进行切分,得到一个打散所有单词的列表
val wordList1 : List[Array[String]] = stringList.map(_.split(" "))
val wordList2 : List[String] = wordList1.flatten
println(wordList2)
val wordList = stringList.flatMap(_.split(" "))
println(wordList)
// 对相同的单词进行分组
val groupMap = wordList.groupBy(word => word)
println(groupMap)
// 对分组之后的list取长度,得到每个单词的个数
val countMap = groupMap.map(kv => (kv._1, kv._2.length))
println(countMap)
val sortList : List[(String, Int)] = countMap.toList
.sortWith(_._2 > _._2)
.take(3)
println(sortList)
}
/*
* 输出结果
* List(hello, hello, world, hello, scala, hello, spark, from, scala, hello, fink, from, scala)
List(hello, hello, world, hello, scala, hello, spark, from, scala, hello, fink, from, scala)
Map(fink -> List(fink), world -> List(world), spark -> List(spark), scala -> List(scala, scala, scala), from -> List(from, from), hello -> List(hello, hello, hello, hello, hello))
Map(fink -> 1, world -> 1, spark -> 1, scala -> 3, from -> 2, hello -> 5)
List((fink,1), (world,1), (spark,1), (scala,3), (from,2), (hello,5))
List((hello,5), (scala,3), (from,2))
*
* */
}
object test1 {
def main(args: Array[String]): Unit = {
val tupleList : List[(String, Int)] = List (
("hello", 1),
("hello world", 2),
("hello scala", 3),
("hello spark from scala", 1),
("hello fink from scala", 2)
)
// 思路一:直接展开尾普通版本
val newStringList = tupleList.map(
kv => {
(kv._1.trim + " ") * kv._2
}
)
println(newStringList)
val wordCountList = newStringList
.flatMap(_.split(" ")) // 空格分词
.groupBy(word => word) // 单词分组
.map(kv => (kv._1, kv._2.size)) // 统计出每个单词的个数
.toList
.sortBy(_._2)(Ordering[Int].reverse)
.take(3)
println(wordCountList)
// 思路二
val preCountList : List[(String, Int)] = tupleList.flatMap(
tuple => {
val strings : Array[String] = tuple._1.split(" ")
strings.map(word => (word, tuple._2))
}
)
println(preCountList)
// 对二元组按照单词进行分组
val preCountMap = preCountList.groupBy(_._1)
println(preCountMap)
// 叠加每个单词的个数值
val countMap = preCountMap.mapValues(
tupleList => tupleList.map(_._2).sum
)
println(countMap)
// 转换成List,排序取前三
val countList = countMap.toList
.sortWith(_._2 > _._2)
.take(3)
println(countList)
}
/*
输出结果
List(hello , hello world hello world , hello scala hello scala hello scala , hello spark from scala , hello fink from scala hello fink from scala )
List((hello,9), (scala,6), (from,3))
List((hello,1), (hello,2), (world,2), (hello,3), (scala,3), (hello,1), (spark,1), (from,1), (scala,1), (hello,2), (fink,2), (from,2), (scala,2))
Map(fink -> List((fink,2)), world -> List((world,2)), spark -> List((spark,1)), scala -> List((scala,3), (scala,1), (scala,2)), from -> List((from,1), (from,2)), hello -> List((hello,1), (hello,2), (hello,3), (hello,1), (hello,2)))
Map(fink -> 2, world -> 2, spark -> 1, scala -> 6, from -> 3, hello -> 9)
List((hello,9), (scala,6), (from,3))
* */
}
object test1 {
def main(args: Array[String]): Unit = {
// 创建一个可变队列
val q = new mutable.Queue[String]()
q.enqueue("a", "b", "c", "d", "fff")
println(q)
println(q.dequeue())
/*
* Queue(a, b, c, d, fff)
a
* */
}
}
scala提供了并行集合,可用于多核环境的并行计算
object test1 {
def main(args: Array[String]): Unit = {
val strings = (1 to 100).map(
x => Thread.currentThread.getName
)
println(strings)
val strings2 = (1 to 100).par.map(
x => Thread.currentThread.getName
)
println(strings2)
/*
* Vector(main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main, main)
ParVector(scala-execution-context-global-20, scala-execution-context-global-20, scala-execution-context-global-20, scala-execution-context-global-20, scala-execution-context-global-20, scala-execution-context-global-20, scala-execution-context-global-30, scala-execution-context-global-30, scala-execution-context-global-30, scala-execution-context-global-20, scala-execution-context-global-30, scala-execution-context-global-20, scala-execution-context-global-26, scala-execution-context-global-26, scala-execution-context-global-26, scala-execution-context-global-29, scala-execution-context-global-28, scala-execution-context-global-25, scala-execution-context-global-33, scala-execution-context-global-33, scala-execution-context-global-33, scala-execution-context-global-31, scala-execution-context-global-32, scala-execution-context-global-34, scala-execution-context-global-22, scala-execution-context-global-22, scala-execution-context-global-22, scala-execution-context-global-22, scala-execution-context-global-22, scala-execution-context-global-22, scala-execution-context-global-22, scala-execution-context-global-34, scala-execution-context-global-34, scala-execution-context-global-34, scala-execution-context-global-34, scala-execution-context-global-34, scala-execution-context-global-34, scala-execution-context-global-25, scala-execution-context-global-25, scala-execution-context-global-25, scala-execution-context-global-32, scala-execution-context-global-32, scala-execution-context-global-32, scala-execution-context-global-31, scala-execution-context-global-31, scala-execution-context-global-31, scala-execution-context-global-31, scala-execution-context-global-31, scala-execution-context-global-31, scala-execution-context-global-31, scala-execution-context-global-21, scala-execution-context-global-21, scala-execution-context-global-21, scala-execution-context-global-32, scala-execution-context-global-32, scala-execution-context-global-32, scala-execution-context-global-28, scala-execution-context-global-28, scala-execution-context-global-28, scala-execution-context-global-28, scala-execution-context-global-28, scala-execution-context-global-28, scala-execution-context-global-24, scala-execution-context-global-24, scala-execution-context-global-24, scala-execution-context-global-24, scala-execution-context-global-24, scala-execution-context-global-24, scala-execution-context-global-29, scala-execution-context-global-29, scala-execution-context-global-29, scala-execution-context-global-29, scala-execution-context-global-29, scala-execution-context-global-29, scala-execution-context-global-29, scala-execution-context-global-23, scala-execution-context-global-23, scala-execution-context-global-23, scala-execution-context-global-23, scala-execution-context-global-23, scala-execution-context-global-23, scala-execution-context-global-23, scala-execution-context-global-23, scala-execution-context-global-23, scala-execution-context-global-23, scala-execution-context-global-23, scala-execution-context-global-23, scala-execution-context-global-27, scala-execution-context-global-27, scala-execution-context-global-27, scala-execution-context-global-27, scala-execution-context-global-27, scala-execution-context-global-27, scala-execution-context-global-35, scala-execution-context-global-35, scala-execution-context-global-35, scala-execution-context-global-24, scala-execution-context-global-25, scala-execution-context-global-32, scala-execution-context-global-22)
* */
}
}
类似java中的switch语法
object test1 {
def main(args: Array[String]): Unit = {
var a: Int = 1
var b: Int = 2
def result(x : Int) = x match {
case 1 => a + b
case 2 => a - b
case 3 => a * b
case 4 => a / b
case _ => "illegal"
}
println(result(1))
}
}
如果向匹配某个范围的数据,可以增加条件守卫
object test1 {
def main(args: Array[String]): Unit = {
def abs(x: Int) = x match {
case i: Int if i >= 0 => i
case j: Int if j < 0 => -j
case _ => "illegal"
}
println(abs(-5))
}
}
def describe(x: Any) = x match {
case 5 => "Int five"
case "hello" => "String hello"
case true => "Boolean true"
case '+' => "Char +"
}
object test1 {
def describe(x: Any) = x match {
case i: Int => "Int"
case s: String => "String hello"
case m: List[_] => "List"
case c: Array[Int] => "Array[Int]"
case something => "something else " + something
}
def main(args: Array[String]): Unit = {
println(describe(List(1, 2, 3, 4, 5)))
println(describe(Array(1, 2, 3, 4, 5, 6)))
println(describe(Array("abc")))
}
/*
* List
Array[Int]
something else [Ljava.lang.String;@2a5ca609
*
* */
}
object test1 {
def main(args: Array[String]): Unit = {
for (arr <- Array(Array(0), Array(1, 0), Array(0, 1, 0),
Array(1, 1, 0), Array(1, 1, 0, 1), Array("hello", 90))) {
val result = arr match {
case Array(0) => "0" //匹配 Array(0) 这个数组
case Array(x, y) => x + "," + y //匹配有两个元素的组,然后将将元素值赋给对应的 x,y
case Array(0, _*) => "以 0 开头的数组" //匹配以 0 开头数组
case _ => "something else"
}
println("result = " + result)
}
}
}
/*
* result = 0
result = 1,0
result = 以 0 开头的数组
result = something else
result = something else
result = hello,90
*
* */
object test1 {
def main(args: Array[String]): Unit = {
//list 是一个存放 List 集合的数组
// 输出列表元素
for (list <- Array(List(0), List(1, 0), List(0, 0, 0), List(1,
0, 0), List(88))) {
val result = list match {
case List(0) => "0" //匹配 List(0)
case List(x, y) => x + "," + y //匹配有两个元素的 List
case List(0, _*) => "0 ..."
case _ => "something else"
}
println(result)
}
}
}
/*
* 0
1,0
0 ...
something else
something else
* */
object test1 {
def main(args: Array[String]): Unit = {
val list: List[Int] = List(1, 2, 5, 6, 7)
list match {
case first :: second :: rest => println(first + "-" +
second + "-" + rest)
case _ => println("something else")
}
}
}
/*
* 1-2-List(5, 6, 7)
* */
object test1 {
def main(args: Array[String]): Unit = {
//对一个元组集合进行遍历
for (tuple <- Array((0, 1), (1, 0), (1, 1), (1, 0, 2))) {
val result = tuple match {
case (0, _) => "0 ..." //是第一个元素是 0 的元组
case (y, 0) => "" + y + "0" // 匹配后一个元素是 0 的对偶元组
case (a, b) => "" + a + " " + b
case _ => "something else" //默认
}
println(result)
}
}
}
/*
* 0 ...
10
1 1
something else
* */
object test1 {
def main(args: Array[String]): Unit = {
val user = User("zhangsan", 1)
val result = user match {
case User("zhangsan", 11) => "yes"
case _ => "no"
}
println(result)
}
}
class User(val name: String, val age: Int)
object User {
def apply(name: String, age: Int): User = new User(name, age)
def unapply(user: User): Option[(String, Int)] = {
if (user == null)
None
else
Some((user.name, user.age))
}
}
object test1 {
def main(args: Array[String]): Unit = {
val user = User("zhangsan", 1)
val result = user match {
case User("zhangsan", 11) => "yes"
case _ => "no"
}
println(result)
}
}
case class User(name: String, age: Int)
val list = list.map {
case (word, count) => (word, count * 2)
}
object test1 {
def main(args: Array[String]): Unit = {
try {
var n = 10 / 0
} catch {
case ex: ArithmeticException => {
// 发生算术异常
println("发生算术异常")
}
case ex: Exception => {
// 对异常处理
println("发生了异常 1")
println("发生了异常 2")
}
} finally {
println("finally")
}
}
@throws(classOf[NumberFormatException])
def f11()={
"abc".toInt
}
}
隐式转换可以在不修改任何代码的情况下,扩展某个类的功能
object test1 {
def main(args: Array[String]): Unit = {
// 隐式函数
implicit def convert(num : Int) = new MyRichInt(num)
println(12.myMax(15))
// 隐式类
implicit class MyRichInt2(val self : Int) {
// 自定义比较大小方法
def myMax2(n : Int) : Int = if (n < self) self else n
def myMin2(n : Int) : Int = if (n < self) n else self
}
println(12.myMax2(15))
// 隐式参数
implicit val str : String = "a"
def sayHello(implicit name :String) = {
println(name)
}
sayHello
}
}
// 自定义类
class MyRichInt(val self : Int) {
// 自定义比较大小方法
def myMax(n : Int) : Int = if (n < self) self else n
def myMin(n : Int) : Int = if (n < self) n else self
}