如何从Scala中的Set中删除元素?
Scala集
在Scala中,集合是相同类型元素的集合。该集合的所有元素都是唯一的,即不允许任何元素。集可以是可变的,也可以是不变的。
示例
Set(1, 4, 5, 7, 12, 87, 213)
在Scala中,您可以从可变集和不可变集中删除元素。对于可变集和不可变集,此操作的处理方式有所不同。
1)从可变集中删除元素
为了删除可变集合的元素,我们将使用-=,-=,retain,clear,remove。
示例1:使用-=和-=方法
object MyClass {
def main(args: Array[String]) {
val set = scala.collection.mutable.Set(2, 56, 577,12 , 46, 19, 90 , 32, 75, 81)
println("The set is "+set)
set -= 2;
println("After deletion of one element, the set is "+set)
set --= List(577, 12, 19);
println("After deletion of multiple elements, the set is "+set)
}
}输出结果
The set is HashSet(32, 81, 577, 2, 19, 56, 90, 75, 12, 46) After deletion of one element, the set is HashSet(32, 81, 577, 19, 56, 90, 75, 12, 46) After deletion of multiple elements, the set is HashSet(32, 81, 56, 90, 75, 46)
范例2:
object MyClass {
def main(args: Array[String]) {
val set = scala.collection.mutable.Set(2, 56, 577,12 , 46, 19, 90 , 32, 75, 81);
println("The set is "+set)
set.retain(_ >20);
println("After deletion using retain, the set is "+set)
set.remove(577)
println("After deletion using remove, the set is "+set)
set.clear()
println("After deletion using clear, the set is "+set)
}
}输出结果
The set is HashSet(32, 81, 577, 2, 19, 56, 90, 75, 12, 46) After deletion using retain, the set is HashSet(32, 81, 577, 56, 90, 75, 46) After deletion using remove, the set is HashSet(32, 81, 56, 90, 75, 46) After deletion using clear, the set is HashSet()
2)从不可变集中删除元素
不变集中的元素无法更改。因此,为了对这些类型的集合执行删除操作,我们需要为每个操作创建一个新副本。-和-操作有效。
示例
object MyClass {
def main(args: Array[String]) {
val set = scala.collection.mutable.Set(2, 56, 577,12 , 46, 19, 90 , 32, 75, 81);
println("The set is "+set)
var set1 = set - 2;
println("After deletion of one element, the set is "+set1)
var set2 = set1 -- List(577, 12, 19);
println("After deletion of multiple elements, the set is "+set2)
var set3 = set2 - (81, 46)
println("After deletion of multiple elements, the set is "+set2)
var set4 = set3 -- Array(56, 90);
println("After deletion of multiple elements, the set is "+set2)
}
}输出结果
The set is HashSet(32, 81, 577, 2, 19, 56, 90, 75, 12, 46) After deletion of one element, the set is HashSet(32, 81, 577, 19, 56, 90, 75, 12, 46) After deletion of multiple elements, the set is HashSet(32, 81, 56, 90, 75, 46) After deletion of multiple elements, the set is HashSet(32, 81, 56, 90, 75, 46) After deletion of multiple elements, the set is HashSet(32, 81, 56, 90, 75, 46)
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短