Scala
只是学习无基本理论
安装Scala
装前必须有jdk
windows安装
解压缩 D:dev/scala
配置环境变量
SCALA_HONE
path
cmd检查
Scala -version
直接输入Scala 控制台运行
idea安装与运行Scala
idea-->插件-->scala-->安装-->重启
新建maven项目
catalog-->maven
archetype-->
项目结构-->全局库-->添加Scala
添加应用支持-->scala
add开头
新建Scala类 选择 object
scala 完全面向对象
scala风格与java风格
public class JavaDemo01 {
public static void main(String[] args) {
System.out.println("我爱你中国");
}
}
javac JavaDemo01
object ScalaDemo01{
def main(args: Array[String]): Unit = {
print("我爱你中国")
}
}
scalac ScalaDemo01
终端运行Scala
编码 utf-8
scalac 文件名字--> 生成 文件名字$.class 与 文件名字.class-->调用 文件名字.class
Scala项目启动方式
main函数与extends app特质的区别:
App是scala语言内置的一个特质,使用它,则把对应object内部的整体作为scala main的一部分,有延迟启动的特性。
同时,命令行参数args也作为App特质的一部分,可以被开发者直接使用。而main函数则是scala的默认启动方式。
使用main函数
object ScalaDemo02{
def main(args: Array[String]): Unit = {
print("我爱你中国")
}
}
使用App特质
object ScalaDemo03 extends App{
print("我爱你中国")
}
object ScalaDemo04 extends App{
print(args(0))
}
终端运行:
scalac ScalaDemo04.scala
scala ScalaDemo04 lhz
Scala代码与Java代码混用
object ScalaDemo05{
def main(args: Array[String]): Unit = {
System.out.println("我爱你中国")
}
}
在 Scala 代码中 可以直接使用 Java 代码
注意:main 方法使用Scala 风格
变量与常量
object ScalaDemo06{
def main(args: Array[String]): Unit = {
// var 变量 修饰符
var a:Int = 10
// val 常量 修饰符
val b:Int = 10
a = 20
println(a)
/**
*报错
*reassignment to val
*/
// b = 20
}
}
字符串基本使用
object ScalaDemo07{
def main(args: Array[String]): Unit = {
var str01:String = "我爱你"
var str02:String = "中国"
// java 风格
println (str01 + str02)
// 插值方式 与 python 风格比较相像
var slogan:String = "桃李不言下自成蹊"
println(s"slogan >>> $slogan")
println("""
|我爱你中国
|亲爱的母亲
""".strpMargin)
}
}
选择结构
object ScalaDemo08{
def main(args: Array[String]): Unit = {
var weekDay:Int = 1
if (weekDay == 1){
println("周一")
}else if (weekDay == 2){
println("周二")
}else if (weekDay == 3){
println("周三")
}else if (weekDay == 4){
println("周四")
}else if (weekDay == 5){
println("周五")
}else if (weekDay == 6){
println("周六")
}else{
println("周日")
}
}
}
循环结构
object ScalaDemo09{
def main(args: Array[String]): Unit = {
var count:Int = 0
while(count<5){
println(count)
count += 1
}
}
}
object ScalaDemo10{
def main(args: Array[String]): Unit = {
//Range 1 to 5
println(1 to 5)
println(1.to(5))
println(1 until 5)
println(1.until(5))
// <- 赋值
for (i <- 0 until 5){
println(i)
}
println("--------------------^_ ~ _^----------------------")
// 求偶数值
for (i <- 0 until 10){
if (i % 2 == 0){
println(i)
}
}
println("--------------^_ ~ _^----------------")
for (i <- 0 until 10 if i % 2 == 0){
println(i)
}
println("--------------^_ ~ _^----------------")
for (i <- 0 until 10 by(2)){
println(i)
}
println("--------------------^_ ~ _^----------------------")
// 增强for循环
var courses = Array("Hadoop","Hive","Sqoop","Flume","Hbase","Phoenix","Presto")
for (course <- courses){
println(course)
}
}
}
函数
无参数 无返回值
object ScalaDemo01{
def main(args: Array[String]): Unit = {
sayHi()
}
// def 函数定义关键字
// sayHI 函数名称
// () 函数参数
// :后面的数据类型为返回值数据类型
// : Unit 无返回值的数据类型占位符
// {} 方法体
private def sayHi(): Unit = {
println("无参数 无返回值 函数 sayHi")
}
}
有参数 无返回值
object ScalaDemo02{
def main(args: Array[String]): Unit = {
sayHi(msg = "hello word")
}
private def sayHi(msg:String): Unit = {
println("有参数 无返回值 函数 sayHi")
println(s"参数是 >>> ${msg}")
}
}
默认参数 无返回值
object ScalaDemo03{
def main(args: Array[String]): Unit = {
sayHi()
sayHi(msg = "hello")
}
private def sayHi(msg:String = "hi"): Unit = {
println("默认参数 无返回值 函数 sayHi")
println(s"参数是 >>> ${msg}")
}
}
# 输出结果:
默认参数 无返回值 函数 sayHi
参数是 >>> hi
默认参数 无返回值 函数 sayHi
参数是 >>> hello
有参数 有返回值
object ScalaDemo04{
def main(args: Array[String]): Unit = {
println(sum(10,20))
}
def sum(a:Int , b:Int): Int ={
// 函数的最后一行为返回值
a+b
}
}
可变参数 无返回值
public class JavaDemo04{
public static void main(String[] args) {
}
private static String
}
object ScalaDemo05{
def main(args: Array[String]): Unit = {
println(format())
println(format(numbers = 1))
println(format(numbers = 1,2))
}
def format(numbers: Int*): String = {
// var result:String = null
var result:Int = 0
if(numbers.size > 0){
for(number <- numbers){
result += number
}
}
result
}
}
面向对象
类与对象
object ScalaDemo01{
def main(args: Array[String]): Unit = {
val person = new Person01
person.name = "lhz"
println(person.name)
}
class Person01{
// _ 代表着 占位符 占位
var name:String = _
}
}
封装
scala中属性、方法默认为public
private只在类的内部和伴生对象中可用
protected,同类、子类可以访问,同包无法访问
private[包名],增加包访问权限,包名下的其他类也可以使用
Scala提供进一步的封装,“public”属性底层实际上都是private,访问时本质上是调用了xxx(get) 和 xxx_eq$(set) 方法,
但这里的方法名并不是getXXX和setXXX,由于一些Java框架会利用反射调用getXXX和setXXX,
因此Scala也提供了上面提到过的@BeanProperty注解去生成某属性的这两个方法,
但注意@BeanProperty不能加在private修饰的属性上,
可以理解为由于“public”本身就是private,将变量修饰为private然后再提供getter、setter方法比较冗余,Scala不推荐这样做。
// 假 封装
object ScalaDemo02{
def main(args: Array[String]): Unit = {
val person = new Person02
person.setName("lhz")
println(person.getName)
person.name = "lz"
println(person.name)
}
class Person02{
// _ 代表着 占位符 占位
@BeanProperty
var name:String = _
}
}
// private 不推荐
// 手写 set get 方法
object ScalaDemo03 {
def main(args: Array[String]): Unit = {
val person = new Person03
person.setName("lhz")
println(person.getName)
}
class Person03{
private var name: String = _
def getName: String = {
this.name
}
def setName(name: String): Unit ={
this.name = name
}
}
}
java代码混用
public class Person04 {
private String realName;
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
}
object ScalaDemo04 {
def main(args: Array[String]): Unit = {
val person = new Person04
person.setRealName("李昊哲")
println(person.getRealName)
}
}
构造函数
object ScalaDemo05{
def main(args: Array[String]): Unit = {
val person01 = new Person05("person01","220422198311222011")
val person02 = new Person05("person02","220422198311222011",15311484567L)
val person03 = new Person05("person02","220422198311222011","我爱你中国")
val person04 = new Person05("person02","220422198311222011",15311484568L,"我爱你中国")
println(person01)
println(person02)
println(person03)
println(person04)
}
}
//主构造函数
class Person05(val realName:String, val idCard:String){
println("Person05 主构造器 执行了")
var mobile: Long= _
var slogan: String= _
// 辅助构函数 辅助构函数不能有类型注解
def this(realName: String , idCard: String, mobile: Long)={
// 辅助构函数 的 第一行代码必须调用 主构造函数 或者其他 辅助构函数
this(realName,idCard)
this.mobile = mobile
}
def this(realName: String , idCard: String, Slogan: String)={
// 辅助构函数 的 第一行代码必须调用 主构造函数 或者其他 辅助构函数
this(realName,idCard)
this.slogan = slogan
}
def this(realName: String , idCard: String, mobile: Long, slogan: String)={
// 辅助构函数 的 第一行代码必须调用 主构造函数 或者其他 辅助构函数
this(realName,idCard,mobile)
this.slogan = slogan
}
override def toString: String =
this.getClass.getSimpleName +
", realName:" + realName +
", idCard:"+ idCard +
", mobile:" + mobile +
", slogan:" + slogan
}
运行结果
Person05 主构造器 执行了
Person05 主构造器 执行了
Person05 主构造器 执行了
Person05 主构造器 执行了
Person05, realName:person01, idCard:220422198311222011, mobile:0, slogan:null
Person05, realName:person02, idCard:220422198311222011, mobile:15311484567, slogan:null
Person05, realName:person02, idCard:220422198311222011, mobile:0, slogan:我爱你中国
Person05, realName:person02, idCard:220422198311222011, mobile:15311484568, slogan:我爱你中国
继承
object ScalaDemo06 {
def main(args: Array[String]): Unit = {
val worker = new Worker("李昊哲", "15311484568", "架构师")
println(worker)
}
}
// 主构造函数
class Person06(val realName: String, val mobile: String) {
println("Person06 主构造器 执行了")
override def toString: String =
this.getClass.getSimpleName +
", realName:" + realName +
", mobile:" + mobile
}
class Worker(realName: String, mobile: String, job: String) extends Person06(realName, mobile) {
println("Worker 主构造器 执行了")
override def toString: String =
this.getClass.getSimpleName +
", realName:" + realName +
", mobile:" + mobile +
", job:" + job
}
抽象类
object ScalaDemo07 {
def main(args: Array[String]): Unit = {
val teacher = new Teacher
teacher.realName = "李昊哲"
teacher.mobile = "15311484568"
println(teacher)
teacher.hi()
}
}
abstract class Person07() {
println("Person07 主构造器 执行了")
var realName: String
var mobile: String
def hi(): Unit
override def toString: String =
this.getClass.getSimpleName +
", realName:" + realName +
", mobile:" + mobile
}
class Teacher extends Person07 {
println("Teacher 主构造器 执行了")
override def toString: String =
this.getClass.getSimpleName +
", realName:" + realName +
", mobile:" + mobile
override var realName: String = _
override var mobile: String = _
override def hi(): Unit = {
println("接着奏乐 接着舞")
}
}
伴生类与伴生对象
scala中的类不能定义静态成员,而代之以定义单例对象来替代
单例对象通过object关键字来声明
单例对象中的所有方法,可以直接通过object单例对象的名字直接来调用。
一个单例对象可以绑定在一个类,当单例对象和某个类写在同一个源文件且共享一个名字,它们就产生了绑定关系。
此时单例对象称之为该类的伴生对象,类称之为该对象的伴生类。
类和它的伴生对象可以互相访问其私有成员
单例对象不能new,所以也没有构造参数
可以把单例对象当做java中可能会用到的静态方法工具类。
作为程序入口的方法必须是静态的,所以main方法必须处在一个单例对象中,而不能写在一个类中。
object ScalaDemo08 {
def main(args: Array[String]): Unit = {
Food.printMsg()
new Food().printSlogan()
}
}
class Food {
private val msg: String = "hello"
def printSlogan(): Unit = {
println(Food.slogan)
}
}
object Food {
private val slogan: String = "桃李不言下自成蹊"
def printMsg(): Unit = {
println(new Food().msg)
}
}
apply
object ScalaDemo09 {
def main(args: Array[String]): Unit = {
// Drink() 相当于 Drink.apply
Drink()
new Drink().apply()
}
}
class Drink{
def apply(): Unit = {
println("class Food 执行...")
}
}
object Drink {
def apply(): Unit = {
println("object Food 执行...")
}
}
数据结构
Array数组
Java
public class JavaDemo01 {
public static void main(String[] args) {
String[] courses = new String[5];
courses[0] = "hadoop";
System.out.println(courses[0]);
String[] hobbies = {"swim", "walk", "photography"};
for (String hobby : hobbies) {
System.out.println(hobby);
}
}
}
scala
object ScalaDemo01 {
def main(args: Array[String]): Unit = {
val courses = new Array[String](5)
println(courses.length)
courses(0) = "hadoop";
println(courses(0))
val hobbies = Array("swim", "walk", "photography")
for (hobby <- hobbies) {
println(hobby)
}
}
}
Array常用方法
object ScalaDemo02 {
def main(args: Array[String]): Unit = {
val numbers = Array(2,4,6,8,0,1,3,5,7,9)
// 求和
val sumResult = numbers.sum
println("sumResult = " + sumResult)
// 最大值
val maxResult = numbers.max
println("maxResult = " + maxResult)
// 最小值
val minResult = numbers.min
println("minResult = " + minResult)
// 排序
val sortedNumbers = numbers.sorted
for (number <- sortedNumbers){
println(number)
}
println("++++++++++++++++++++")
val reverseNumbers = sortedNumbers.reverse
for (number <- reverseNumbers) {
println(number)
}
}
}
可变长Array
object ScalaDemo03 {
def main(args: Array[String]): Unit = {
val courses = ArrayBuffer[String]()
courses += "hadoop"
courses += "hive"
courses += "Chinese"
courses += "math"
courses ++= Array("presto","hbase","phoenix","scala","spark")
// 在下标 1 的位置插入
courses.insert(1,"logger")
// 移除 下标 5 的内容
courses.remove(5)
// 移除 下标 2-4 的内容
courses.remove(2,4)
for (course <- courses){
println(course)
}
}
}
List 集合
Scala 列表类似于数组,它们所有元素的类型都相同,
但是它们也有所不同:列表是不可变的,值一旦被定义了就不能改变,
其次列表 具有递归的结构(也就是链接表结构)而数组不是。
object ScalaDemo04 {
def main(args: Array[String]): Unit = {
val courses = List("presto","hbase","phoenix","scala","spark")
for (course <- courses) {
println(course)
}
}
}
object ScalaDemo05 {
def main(args: Array[String]): Unit = {
val courses = ListBuffer[String]()
courses += "hadoop"
courses += "hive"
courses ++= List("presto", "hbase", "phoenix", "scala", "spark")
for (course <- courses) {
println(course)
}
}
}
object ScalaDemo06 {
def main(args: Array[String]): Unit = {
val courses = ListBuffer[String]()
courses += "hadoop"
courses += "hive"
courses ++= List("presto", "hbase", "phoenix", "scala", "spark")
println(courses.head)
println(courses.tail)
}
}
Nil
object ScalaDemo07 {
def main(args: Array[String]): Unit = {
println(Nil)
val courses = "hadoop" :: "presto" :: "hbase" :: Nil
println("courses 元素数量 >>> " + courses.size)
for (course <- courses) {
println(course)
}
}
}
Set
Scala Set(集合)是没有重复的对象集合,所有的元素都是唯一的。
Scala 集合分为可变的和不可变的集合。
默认情况下,Scala 使用的是不可变集合,如果你想使用可变集合,需要引用 scala.collection.mutable.Set 包。
object ScalaDemo08 {
def main(args: Array[String]): Unit = {
val courses = Set("presto","hbase","phoenix","scala","spark","hbase","scala")
for (course <- courses) {
println(course)
}
}
}
object ScalaDemo09 {
def main(args: Array[String]): Unit = {
val courses = mutable.HashSet[String]()
courses += "hadoop"
courses += "hive"
courses ++= List("presto", "hbase", "phoenix", "scala", "spark")
for (course <- courses) {
println(course)
}
}
}
Map
object ScalaDemo10 {
def main(args: Array[String]): Unit = {
val a = Map("k1" -> "v1", "k2" -> "v2", "k3" -> "v3")
println(a("k1"))
// java.util.NoSuchElementException: key not found: k5
// println(a("k5"))
println(a.getOrElse("k1",null))
println(a.getOrElse("k5",null))
}
}
object ScalaDemo11 {
def main(args: Array[String]): Unit = {
val map = mutable.HashMap[String, String]()
map += ("k1" -> "v1")
println(map.getOrElse("k1", null))
}
}
object ScalaDemo12 {
def main(args: Array[String]): Unit = {
val map = mutable.HashMap[String, String]()
map += ("k1" -> "v1")
map += ("k2" -> "v2")
map += ("k3" -> "v3")
map += ("k4" -> "v4")
map += ("k5" -> "v5")
for ((key, value) <- map) {
println(key + " >>> " + value)
}
}
}
object ScalaDemo13 {
def main(args: Array[String]): Unit = {
val map = mutable.HashMap[String, String]()
map += ("k1" -> "v1")
map += ("k2" -> "v2")
map += ("k3" -> "v3")
map += ("k4" -> "v4")
map += ("k5" -> "v5")
val keySet = map.keySet
for (key <- keySet) {
println(key + " >>> " + map.getOrElse(key, null))
}
}
}
object ScalaDemo13 {
def main(args: Array[String]): Unit = {
val map = mutable.HashMap[String, String]()
map += ("k1" -> "v1")
map += ("k2" -> "v2")
map += ("k3" -> "v3")
map += ("k4" -> "v4")
map += ("k5" -> "v5")
val values = map.values
for (value <- values) {
println(value)
}
}
}
object ScalaDemo14 {
def main(args: Array[String]): Unit = {
val map = mutable.HashMap[String, String]()
map += ("k1" -> "v1")
map += ("k2" -> "v2")
map += ("k3" -> "v3")
map += ("k4" -> "v4")
map += ("k5" -> "v5")
for ((key, _) <- map) {
println(key + " >>> " + map.getOrElse(key, null))
}
}
}
Tuple
与列表一样,元组也是不可变的,但与列表不同的是元组可以包含不同类型的元素。
元组的值是通过将单个的值包含在圆括号中构成的
object ScalaDemo15 {
def main(args: Array[String]): Unit = {
val t1 = (1, 3.14, "李昊哲")
for (i <- 0 until (t1.productArity)) {
println(t1.productElement(i))
}
val protocol: String = "http"
val domain: String = "localhost"
val port: Int = 80
val context: String = "lhz"
val url = (protocol, domain, port, context)
println(url._1)
println(url._2)
println(url._3)
println(url._4)
}
}
异常机制
object ScalaDemo01 {
def main(args: Array[String]): Unit = {
try {
println(1 / 1)
println(1 / 0)
} catch {
case e: ArithmeticException => println("数学异常")
} finally {
println("释放资源")
}
}
}
匹配模式
java switch
从java14开始, switch语句有了一个很大的调整, 这就让swicth语句有了更多的操作和选择,在代码上,更加的简便灵活.
- switch 标准方式
- switch - > 用法:
- switch yield 用法:
标准方式
public class JavaDemo01 {
public static void main(String[] args) {
int dayOfWeek = 2;
switch (dayOfWeek) {
case 1:
System.out.println("星期一");
case 2:
System.out.println("星期二");
case 3:
System.out.println("星期三");
case 4:
System.out.println("星期四");
case 5:
System.out.println("星期五");
case 6:
System.out.println("星期六");
default:
System.out.println("星期日");
}
}
}
从输出结果发现case代码块被穿透了,使用break防止case代码执行穿透,代码如下:
public class JavaDemo02 {
public static void main(String[] args) {
int dayOfWeek = 2;
switch (dayOfWeek) {
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
break;
case 3:
System.out.println("星期三");
break;
case 4:
System.out.println("星期四");
break;
case 5:
System.out.println("星期五");
break;
case 6:
System.out.println("星期六");
break;
default:
System.out.println("星期日");
break;
}
}
}
switch - > 用法:
使用switch标准方式编写代码太多的break造成代码冗余可读性不高 可以借助函数式接口和lambda表达式简化书写
int dayOfWeek = 2;
switch (dayOfWeek) {
case 1 -> System.out.println("星期一");
case 2 -> System.out.println("星期二");
case 3 -> System.out.println("星期三");
case 4 -> System.out.println("星期四");
case 5 -> System.out.println("星期五");
case 6 -> System.out.println("星期六");
default -> System.out.println("星期日");
}
switch yield 用法:返回值
先来开一段标准模式的代码:
public class JavaDemo04 {
public static void main(String[] args) {
String weekday = null;
int dayOfWeek = 2;
switch (dayOfWeek) {
case 1:
weekday = "星期一";
break;
case 2:
weekday = "星期二";
break;
case 3:
weekday = "星期三";
break;
case 4:
weekday = "星期四";
break;
case 5:
weekday = "星期五";
break;
case 6:
weekday = "星期六";
break;
default:
weekday = "星期日";
break;
}
System.out.println(weekday);
}
}
从上面代码不难看出我们通过条件匹配为变量赋值,再来看看switch yield的简化写法
public class JavaDemo05 {
public static void main(String[] args) {
int dayOfWeek = 2;
String weekday = switch (dayOfWeek) {
case 1:
yield "星期一";
case 2:
yield "星期二";
case 3:
yield "星期三";
case 4:
yield "星期四";
case 5:
yield "星期五";
case 6:
yield "星期六";
default:
yield "星期日";
};
System.out.println(weekday);
}
}
scala math
object ScalaDemo01 {
def main(args: Array[String]): Unit = {
val dayOfWeek: Int = 2
dayOfWeek match {
case 1 => System.out.println("星期一")
case 2 => System.out.println("星期二")
case 3 => System.out.println("星期三")
case 4 => System.out.println("星期四")
case 5 => System.out.println("星期五")
case 6 => System.out.println("星期六")
case _ => System.out.println("星期日")
}
}
}
偏函数
被包在花括号内没有match的一组case语句
输入参数的数据类型
输出参数的数据类型
/**
* 偏函数
* 被包在花括号内没有match的一组case语句
*/
object ScalaDemo02 {
def main(args: Array[String]): Unit = {
val weekDay = chime(2)
println(weekDay)
}
/**
* A 输入参数的数据类型
* B 输出参数的数据类型
* @return
*/
def chime:PartialFunction[Int,String] = {
case 1 => "星期一"
case 2 => "星期二"
case 3 => "星期三"
case 4 => "星期四"
case 5 => "星期五"
case 6 => "星期六"
case _ => "星期日"
}
}
颗粒化函数
object ScalaDemo01 {
def main(args: Array[String]): Unit = {
def sum01(x: Int, y: Int) = x + y
println(sum01(10, 20))
def sum02(x: Int)(y: Int) = x + y
println(sum02(10)(20))
}
}
匿名函数
定义个没有名称的函数我们称之为匿名函数
箭头左边是参数列表,右边是函数体。
object ScalaDemo02 {
def main(args: Array[String]): Unit = {
val result = (x:Int) => x * 2
println(result(10))
}
}
高阶函数
foreach
遍历
public class JavaDemo03 {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
nums.forEach(System.out::println);
}
}
object ScalaDemo03 {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
nums.foreach(num => println(num))
}
}
map
逐个操作列表中每一个元素
public class JavaDemo04 {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
List<Integer> numbers = nums.stream().map(num -> num * 2).toList();
numbers.forEach(System.out::println);
}
}
object ScalaDemo04 {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
val numbers = nums.map(num => num * 2)
numbers.foreach(num => println(num))
}
}
object ScalaDemo05 {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
val numbers = nums.map(_ * 2)
numbers.foreach(num => println(num))
}
}
flatten flatMap
flatMap
flatten
先对集合中每个元素进行map,再对map后的每个元素进行flatten
map后的每个元素也是一个集合
public class JavaDemo06 {
public static void main(String[] args) {
List<Integer> listA = new ArrayList<>();
listA.add(1);
listA.add(2);
List<Integer> listB = new ArrayList<>();
listA.add(5);
listA.add(6);
List<List<Integer>> listC = new ArrayList<>();
listC.add(listA);
listC.add(listB);
List<Integer> numbers = listC.stream().flatMap(Collection::stream).toList();
numbers.forEach(System.out::println);
}
}
object ScalaDemo06 {
def main(args: Array[String]): Unit = {
val nums = List(List(1, 2), List(5, 6))
val numbers = nums.flatten
numbers.foreach(num => println(num))
}
}
filter
过滤出符合规则的数据生成新的列表
public class JavaDemo07 {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
Person person;
for (int i = 0; i < 10; i++) {
person = new Person("user" + (i + 1), (i + 1) % 2);
persons.add(person);
}
// 获取男性列表
List<Person> manList = persons.stream().filter(user -> user.getGender() == 1).toList();
// 获取女性列表
List<Person> womanList = persons.stream().filter(user -> user.getGender() == 0).toList();
manList.forEach(System.out::println);
System.out.println("+++++++++++++++++++++++");
womanList.forEach(System.out::println);
}
}
class Person {
private String name;
private int gender;
public Person() {
}
public Person(String name, int gender) {
this.name = name;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", gender=" + gender +
'}';
}
}
运行结果:
Person{name='user1', gender=1}
Person{name='user3', gender=1}
Person{name='user5', gender=1}
Person{name='user7', gender=1}
Person{name='user9', gender=1}
+++++++++++++++++++++++
Person{name='user2', gender=0}
Person{name='user4', gender=0}
Person{name='user6', gender=0}
Person{name='user8', gender=0}
Person{name='user10', gender=0}
object ScalaDemo07 {
def main(args: Array[String]): Unit = {
val users = new ListBuffer[User]()
var user: User = null
for (i <- 0 until 10) {
user = new User("user" + (i + 1),(i + 1) % 2)
users += user
}
// 获取男性列表
val manList = users.filter(ele => ele.getGender % 2 == 1)
// 获取女性列表
val womanList = users.filter(ele => ele.getGender % 2 == 0)
manList.foreach(man => println(man))
println("+++++++++++++++++++++++")
womanList.foreach(woman => println(woman))
}
}
class User {
@BeanProperty
var name: String = _
@BeanProperty
var gender: Int = _
def this(name:String,gender:Int) = {
this()
this.name = name
this.gender = gender
}
override def toString: String = "User{" + "name='" + name + '\'' + ", gender=" + gender + '}'
}
object ScalaDemo07 {
def main(args: Array[String]): Unit = {
val users = new ListBuffer[User]()
var user: User = null
for (i <- 0 until 10) {
user = new User("user" + (i + 1),(i + 1) % 2)
users += user
}
// 获取男性列表
val manList = users.filter(ele => ele.getGender % 2 == 1)
// 获取女性列表
val womanList = users.filter(ele => ele.getGender % 2 == 0)
manList.foreach(man => println(man))
println("+++++++++++++++++++++++")
womanList.foreach(woman => println(woman))
}
}
class User {
@BeanProperty
var name: String = _
@BeanProperty
var gender: Int = _
def this(name:String,gender:Int) = {
this()
this.name = name
this.gender = gender
}
override def toString: String = "User{" + "name='" + name + '\'' + ", gender=" + gender + '}'
}
运行结果:
User{name='user1', gender=1}
User{name='user3', gender=1}
User{name='user5', gender=1}
User{name='user7', gender=1}
User{name='user9', gender=1}
+++++++++++++++++++++++
User{name='user2', gender=0}
User{name='user4', gender=0}
User{name='user6', gender=0}
User{name='user8', gender=0}
User{name='user10', gender=0}
reduce
相邻两个元素转为一个元素
列表中的所有元素转为一个元素
1, 2, 3, 4, 5, 6, 7, 8, 9
-1, 3, 4, 5, 6, 7, 8, 9
-4, 4, 5, 6, 7, 8, 9
-8, 5, 6, 7, 8, 9
-13, 6, 7, 8, 9
-19, 7, 8, 9
-26, 8, 9
-34, 9
-43
public class JavaDemo08 {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
List<Integer> numbers = nums.stream().reduce((a, b) -> a - b).stream().toList();
numbers.forEach(System.out::println);
}
}
object ScalaDemo08 {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
// val num = nums.reduce((a, b) => a - b)
val num = nums.reduceLeft(_ - _)
println(num)
}
}
reduceLeft
object ScalaDemo09 {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
// val num = nums.reduceLeft((a, b) => a - b)
val num = nums.reduceLeft(_ - _)
println(num)
}
}
reduceRight
1, 2, 3, 4, 5, 6, 7, 8, 9
1, 2, 3, 4, 5, 6, 7, 1
1, 2, 3, 4, 5, 6, -6
1, 2, 3, 4, 5, -12
1, 2, 3, 4, -17
1, 2, 3, -21
1, 2, -24
1, -26
-27
object ScalaDemo10 {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
val num = nums.reduceRight((a, b) => b - a)
println(num)
}
}
// -27
1, 2, 3, 4, 5, 6, 7, 8, 9
1, 2, 3, 4, 5, 6, 7, -1
1, 2, 3, 4, 5, 6, 8
1, 2, 3, 4, 5, -2
1, 2, 3, 4, 7
1, 2, 3, -3
1, 2, 6
1, -4
5
object ScalaDemo10 {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
val num = nums.reduceRight((a, b) => _ - _)
println(num)
}
}
//-27
count
计数器
public class JavaDemo12 {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
long count = nums.stream().filter(num -> num % 2 == 0).count();
System.out.println("列表中偶数是数量 >>> " + count);
}
}
object ScalaDemo12 {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
val count = nums.count(num => num % 2 == 0)
println(count)
}
}
//4
distinct
public class JavaDemo13 {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 5, 6, 7, 8, 9, 3, 4, 5, 7, 8, 2, 3);
List<Integer> numbers = nums.stream().distinct().toList();
numbers.forEach(System.out::println);
}
}
object ScalaDemo13 {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 5, 6, 7, 8, 9, 3, 4, 5, 7, 8, 2, 3);
val numbers = nums.distinct
numbers.foreach(num => println(num))
}
}
sorted
排序类需要实现 Comparable 接口
public class JavaDemo14 {
public static void main(String[] args) {
List<Dog> dogs = new ArrayList<>();
for (int i = 0; i < 10; i++) {
dogs.add(new Dog("dog" + (i + 1), ThreadLocalRandom.current().nextInt(1, 10)));
}
dogs.forEach(System.out::println);
List<Dog> newDogs = dogs.stream().sorted((a, b) -> a.getAge() - b.getAge()).toList();
System.out.println("++++++++++++++");
newDogs.forEach(System.out::println);
}
}
class Dog {
private String name;
private int age;
public Dog() {
}
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
运行结果:
Dog{name='dog1', age=3}
Dog{name='dog2', age=3}
Dog{name='dog3', age=3}
Dog{name='dog4', age=3}
Dog{name='dog5', age=7}
Dog{name='dog6', age=6}
Dog{name='dog7', age=4}
Dog{name='dog8', age=8}
Dog{name='dog9', age=7}
Dog{name='dog10', age=2}
++++++++++++++
Dog{name='dog10', age=2}
Dog{name='dog1', age=3}
Dog{name='dog2', age=3}
Dog{name='dog3', age=3}
Dog{name='dog4', age=3}
Dog{name='dog7', age=4}
Dog{name='dog6', age=6}
Dog{name='dog5', age=7}
Dog{name='dog9', age=7}
Dog{name='dog8', age=8}
object ScalaDemo14 {
def main(args: Array[String]): Unit = {
val random = new Random()
val cats = List(
new Cat("cat1", random.between(1, 10)),
new Cat("cat2", random.between(1, 10)),
new Cat("cat3", random.between(1, 10)),
new Cat("cat4", random.between(1, 10)),
new Cat("cat5", random.between(1, 10)),
new Cat("cat6", random.between(1, 10)),
new Cat("cat7", random.between(1, 10)),
new Cat("cat8", random.between(1, 10)),
new Cat("cat9", random.between(1, 10)),
new Cat("cat10", random.between(1, 10)),
)
cats.foreach(cat => println(cat))
println("++++++++++++++++++++++")
val newCats = cats.sorted
newCats.foreach(cat => println(cat))
}
}
class Cat extends Comparable[Cat] {
@BeanProperty
var name: String = _
@BeanProperty
var age: Int = _
def this(name: String, age: Int) = {
this()
this.name = name
this.age = age
}
override def compareTo(o: Cat): Int = this.getAge - o.getAge
override def toString = s"Cat(name=$name, age=$age)"
}
运行结果:
Cat(name=cat1, age=8)
Cat(name=cat2, age=4)
Cat(name=cat3, age=5)
Cat(name=cat4, age=1)
Cat(name=cat5, age=5)
Cat(name=cat6, age=5)
Cat(name=cat7, age=2)
Cat(name=cat8, age=3)
Cat(name=cat9, age=8)
Cat(name=cat10, age=5)
++++++++++++++++++++++
Cat(name=cat4, age=1)
Cat(name=cat7, age=2)
Cat(name=cat8, age=3)
Cat(name=cat2, age=4)
Cat(name=cat3, age=5)
Cat(name=cat5, age=5)
Cat(name=cat6, age=5)
Cat(name=cat10, age=5)
Cat(name=cat1, age=8)
Cat(name=cat9, age=8)
sortBy
不需要写代码逻辑 只需要制定排序指标即可
object ScalaDemo15 {
def main(args: Array[String]): Unit = {
val random = new Random()
val pigs = List(
new Pig("pig1", random.between(1, 10)),
new Pig("pig2", random.between(1, 10)),
new Pig("pig3", random.between(1, 10)),
new Pig("pig4", random.between(1, 10)),
new Pig("pig5", random.between(1, 10)),
new Pig("pig6", random.between(1, 10)),
new Pig("pig7", random.between(1, 10)),
new Pig("pig8", random.between(1, 10)),
new Pig("pig9", random.between(1, 10)),
new Pig("pig10", random.between(1, 10)),
)
pigs.foreach(pig => println(pig))
println("++++++++++++++++++++++")
// 不需要写代码逻辑 只需要制定排序指标即可
val newPigs = pigs.sortBy(pig => pig.getAge)
newPigs.foreach(pig => println(pig))
}
}
class Pig {
@BeanProperty
var name: String = _
@BeanProperty
var age: Int = _
def this(name: String, age: Int) = {
this()
this.name = name
this.age = age
}
override def toString = s"Pig(name=$name, age=$age)"
}
运行结果:
Pig(name=pig2, age=8)
Pig(name=pig3, age=8)
Pig(name=pig4, age=3)
Pig(name=pig5, age=8)
Pig(name=pig6, age=1)
Pig(name=pig7, age=7)
Pig(name=pig8, age=8)
Pig(name=pig9, age=3)
Pig(name=pig10, age=1)
++++++++++++++++++++++
Pig(name=pig6, age=1)
Pig(name=pig10, age=1)
Pig(name=pig1, age=2)
Pig(name=pig4, age=3)
Pig(name=pig9, age=3)
Pig(name=pig7, age=7)
Pig(name=pig2, age=8)
Pig(name=pig3, age=8)
Pig(name=pig5, age=8)
Pig(name=pig8, age=8)
sortWtih
传递一个函数 然后在函数内编写排序规则
object ScalaDemo16 {
def main(args: Array[String]): Unit = {
val random = new Random()
val birds = List(
new Bird("bird1", random.between(1, 10)),
new Bird("bird2", random.between(1, 10)),
new Bird("bird3", random.between(1, 10)),
new Bird("bird4", random.between(1, 10)),
new Bird("bird5", random.between(1, 10)),
new Bird("bird6", random.between(1, 10)),
new Bird("bird7", random.between(1, 10)),
new Bird("bird8", random.between(1, 10)),
new Bird("bird9", random.between(1, 10)),
new Bird("bird10", random.between(1, 10)),
)
birds.foreach(Bird => println(Bird))
println("++++++++++++++++++++++")
// 传递一个函数 然后在函数内编写排序规则
val newBirds = birds.sortWith((a, b) => a.getAge - b.getAge <= 0).toList
newBirds.foreach(bird => println(bird))
}
}
class Bird {
@BeanProperty
var name: String = _
@BeanProperty
var age: Int = _
def this(name: String, age: Int) = {
this()
this.name = name
this.age = age
}
override def toString = s"Bird(name=$name, age=$age)"
}
运行结果:
Bird(name=bird1, age=7)
Bird(name=bird2, age=1)
Bird(name=bird3, age=9)
Bird(name=bird4, age=2)
Bird(name=bird5, age=5)
Bird(name=bird6, age=2)
Bird(name=bird7, age=4)
Bird(name=bird8, age=1)
Bird(name=bird9, age=9)
Bird(name=bird10, age=9)
++++++++++++++++++++++++++
Bird(name=bird8, age=1)
Bird(name=bird2, age=1)
Bird(name=bird6, age=2)
Bird(name=bird4, age=2)
Bird(name=bird7, age=4)
Bird(name=bird5, age=5)
Bird(name=bird1, age=7)
Bird(name=bird10, age=9)
Bird(name=bird9, age=9)
Bird(name=bird3, age=9)
take
TopN
public class JavaDemo17 {
public static void main(String[] args) {
int base = 1000;
ArrayList<Video> videos = new ArrayList<>();
for (int i = 0; i < 10; i++) {
videos.add(new Video(base + i + 1, ThreadLocalRandom.current().nextInt(100, 1000)));
}
videos.forEach(System.out::println);
System.out.println("+++++++++++++");
videos.sort((a, b) -> b.getGold() - a.getGold());
List<Video> topList = videos.stream().limit(3).toList();
topList.forEach(System.out::println);
}
}
运行结果:
Video{vid='1001', gold=566}
Video{vid='1002', gold=548}
Video{vid='1003', gold=620}
Video{vid='1004', gold=897}
Video{vid='1005', gold=264}
Video{vid='1006', gold=311}
Video{vid='1007', gold=882}
Video{vid='1008', gold=870}
Video{vid='1009', gold=106}
Video{vid='1010', gold=185}
+++++++++++++
Video{vid='1004', gold=897}
Video{vid='1007', gold=882}
Video{vid='1008', gold=870}
object ScalaDemo17 {
def main(args: Array[String]): Unit = {
val random = new Random()
val videos = List(
new VideoInfo(1001, random.between(100, 1000)),
new VideoInfo(1001, random.between(100, 1000)),
new VideoInfo(1001, random.between(100, 1000)),
new VideoInfo(1001, random.between(100, 1000)),
new VideoInfo(1001, random.between(100, 1000)),
new VideoInfo(1001, random.between(100, 1000)),
new VideoInfo(1001, random.between(100, 1000)),
new VideoInfo(1001, random.between(100, 1000)),
new VideoInfo(1001, random.between(100, 1000)),
new VideoInfo(1001, random.between(100, 1000))
)
videos.foreach(video => println(video))
println("++++++++++++++++++++++++++++")
val videoSortList = videos.sortWith((a, b) => a.getGold - b.getGold >= 0).toList
val videoTopList = videoSortList.take(3).toList
videoTopList.foreach(video => println(video))
}
}
class VideoInfo {
@BeanProperty
var name: Int = _
@BeanProperty
var gold: Int = _
def this(name: Int, gold: Int) = {
this()
this.name = name
this.gold = gold
}
override def toString = s"VideoInfo(name=$name, gold=$gold)"
}
VideoInfo(name=1001, gold=660)
VideoInfo(name=1002, gold=870)
VideoInfo(name=1003, gold=405)
VideoInfo(name=1004, gold=356)
VideoInfo(name=1005, gold=165)
VideoInfo(name=1006, gold=452)
VideoInfo(name=1007, gold=698)
VideoInfo(name=1008, gold=138)
VideoInfo(name=1009, gold=839)
VideoInfo(name=1010, gold=211)
++++++++++++++++++++++++++++
VideoInfo(name=1002, gold=870)
VideoInfo(name=1009, gold=839)
VideoInfo(name=1007, gold=698)
groupBy
分组
public class JavaDemo18 {
public static void main(String[] args) {
List<Animal> animals = new ArrayList<>();
Animal animal;
for (int i = 0; i < 10; i++) {
animal = new Animal("animal" + (i + 1), (i + 1) % 2);
animals.add(animal);
}
// 按照性别分组
Map<Integer, List<Animal>> animalGenderGroup = animals.stream().collect(Collectors.groupingBy(Animal::getGender));
animalGenderGroup.forEach((key, value) -> System.out.println((key == 1 ? "雄性" : "雌性") + " >>> " + value));
}
}
class Animal {
private String name;
private int gender;
public Animal() {
}
public Animal(String name, int gender) {
this.name = name;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Animal{" +
"name='" + name + '\'' +
", gender=" + gender +
'}';
}
}
运行结果:
雌性 >>> [Animal{name='animal2', gender=0}, Animal{name='animal4', gender=0}, Animal{name='animal6', gender=0}, Animal{name='animal8', gender=0}, Animal{name='animal10', gender=0}]
雄性 >>> [Animal{name='animal1', gender=1}, Animal{name='animal3', gender=1}, Animal{name='animal5', gender=1}, Animal{name='animal7', gender=1}, Animal{name='animal9', gender=1}]
object ScalaDemo18 {
def main(args: Array[String]): Unit = {
val baseName: String = "emp"
val emps = List(
new Emp(baseName + 1001, 1),
new Emp(baseName + 1002, 2),
new Emp(baseName + 1003, 1),
new Emp(baseName + 1004, 2),
new Emp(baseName + 1005, 1),
new Emp(baseName + 1006, 2),
new Emp(baseName + 1007, 2),
new Emp(baseName + 1008, 1),
new Emp(baseName + 1009, 1),
new Emp(baseName + 1010, 1)
)
val deptMap: Map[Int, List[Emp]] = emps.groupBy(_.getDeptId)
for ((deptId, empList) <- deptMap) {
println(deptId + " >>> " + empList)
}
}
}
class Emp {
@BeanProperty
var name: String = _
@BeanProperty
var deptId: Int = _
def this(name: String, deptId: Int) {
this()
this.name = name
this.deptId = deptId
}
override def toString = s"Emp(name=$name, deptId=$deptId)"
}
运行结果:
1 >>> List(Emp(name=emp1001, deptId=1), Emp(name=emp1003, deptId=1), Emp(name=emp1005, deptId=1), Emp(name=emp1008, deptId=1), Emp(name=emp1009, deptId=1), Emp(name=emp1010, deptId=1))
2 >>> List(Emp(name=emp1002, deptId=2), Emp(name=emp1004, deptId=2), Emp(name=emp1006, deptId=2), Emp(name=emp1007, deptId=2))