package com.fuyun.bigdata.scala.collection
/**
* Set集合:数学意义上的集合:无序的,不可重复的(归根于底层实现,使用Map)
* 使用场景:
* 去重,使用set存储数据
*/
object SetDemo {
def main(args: Array[String]): Unit = {
/*
* 对于set和map来说,可变和不可变的类都是一样的名称,只不过所在包名称不一样而已
* 默认为不可变的类
*/
// 创建不可变的set集合
val set1 = Set(3, 3, 6, 6, 8, -9)
// 用分隔符逐一将元素输出
println(set1.mkString(", "))
/*
* max 和 min 函数来说,肯定涉及到集合中元素的比较,
* 所以需要集合中的元素具有可比性(实现比较器接口)
*/
println(s"max = ${set1.max}")
println(s"min = ${set1.min}")
// def maxBy[B](f: A => B): A
// 表示传递的是匿名函数
println(s"${set1.maxBy(item => item*(-2))}")
println(s"${set1.maxBy(Math.abs(_))}")
// 表示的是直接传递某个函数给maxBy高阶函数
println(s"${set1.maxBy(Math.abs)}")
/*
* 可变的set集合
*/
import scala.collection.mutable
val set2 = mutable.Set[Int]()
// 添加元素
set2 += 6
// ++=方法将set集合或列表中每个元素逐一添加
set2 ++= List(1, 1, 6, 5)
set2 ++= Set(2, 2, 5, 5)
// 将可变的set集合转为不可变的set集合,需要指定数据类型
println(s"${set2.toSet[Int].mkString("< ", ", ", " >")}")
// 将set转换为List
println(s"${set2.toList.mkString("< ", ", ", " >")}")
}
}
运行结果:
3, 6, 8, -9
max = 8
min = -9
-9
-9
-9
< 1, 5, 2, 6 >
< 1, 5, 2, 6 >
Process finished with exit code 0