Scala操作列表List、数组Array和集合Set

本文介绍了Scala中List的初始化、过滤筛选、map调用自定义函数和flatMap方法的使用。接着展示了Array的初始化、元素增加以及转换为迭代器的操作。此外,还讲解了可变集合Set的创建和添加元素的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Scala操作List

1.1 初始化List

scala> val list0 = List(9, 2, 8, 3, 4, 5, 6, 7)
list0: List[Int] = List(9, 2, 8, 3, 4, 5, 6, 7)

1.2 List过滤筛选

// 筛选偶数
scala> list0.filter(_ % 2 == 0)
res0: List[Int] = List(2, 8, 4, 6)

list0.filter(_ % 2 == 0) 等价于list0.filter(x => x % 2 == 0)

// 筛选偶数
scala> list0.filter(x => x % 2 == 0)
res1: List[Int] = List(2, 8, 4, 6)
// 筛选不是偶数
scala> list0.filterNot(x => x % 2 == 0)
res2: List[Int] = List(9, 3, 5, 7)

字符串列表过滤操作

// 初始化字符串元素类型的列表
scala> val list_str = List("Nice","To","Meet","You")
list_str: List[String] = List(Nice, To, Meet, You)
// 筛选N开头的
scala> val x = list_str.filter(x => x.startsWith("N"))
x: List[String] = List(Nice)
// 筛选o头的
scala> var y = list_str.filter(x => x.contains("o"))
y: List[String] = List(To, You)
// 筛选长度大于3的
scala> var z = list_str.filter(x => x.length()>3)
z: List[String] = List(Nice, Meet)
// 多次过滤:筛选长度大于3的 => 筛选N开头的
scala> var z = list_str.filter(x => x.length()>3).filter(x=> x.contains("N"))

list_str.filter(x => x.length()>3).filter(x=> x.contains(“N”)) // 多次过滤

1.2 map调用自定义函数

map调用自定义函数

// 自定义函数 => 所有数字 * 2
scala> def mutiple(n:Int):Int={
     |       2*n
     |     }
mutiple: (n: Int)Int

scala> val  list = List(3, 4, 5)
list: List[Int] = List(3, 4, 5)

// map方式调用自定义函数
scala> val list2 = list.map(mutiple)
list2: List[Int] = List(6, 8, 10)

1.3 flatMap方法

迭代器调用flatMap,flatMap对每个元素调用方法

// 初始化字符串类型的List
scala> val listStr01 = List("hello word", "hello hdfs", "hadoop hdfs")
listStr01: List[String] = List(hello word, hello hdfs, hadoop hdfs)

// 按空格拆分
scala> val listStr02 = listStr01.flatMap(_.split(" "))
listStr02: List[String] = List(hello, word, hello, hdfs, hadoop, hdfs)

flatMap 接 操作方法

1.4 foreach方法

// foreach遍历打印元素
scala> listStr02.foreach(println)
hello
word
hello
hdfs
hadoop
hdfs

2、Scala操作Array

2.1 初始化Array

scala> var d : Array[Int] = Array [ Int ] (1, 2, 3, 4, 5)
d: Array[Int] = Array(1, 2, 3, 4, 5)

2.2 ++操作符 增加元素

scala> d ++ Array [ Int ](6)
res15: Array[Int] = Array(1, 2, 3, 4, 5, 6)

2.3 toIterator迭代器

scala> d.toIterator
res17: Iterator[Int] = non-empty iterator

3、集合Set

3.1 创建集合

// 创建可变的集合
scala> var set = scala.collection.mutable.Set[String]()
set: scala.collection.mutable.Set[String] = Set()

mutable.Set是可变的,允许增加集合元素

3.2 集合添加元素

// 添加元素 写法1
scala> set += "A"
res24: scala.collection.mutable.Set[String] = Set(A)

scala> set += "B"
res27: scala.collection.mutable.Set[String] = Set(B, A)

// 添加元素 写法2
scala> set.add("C")
res28: Boolean = true

scala> set
res29: scala.collection.mutable.Set[String] = Set(B, C, A)

set += ‘A’ 等价于 set.add(“A”)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值