Scala如何获取不含被包含元素的集合?
Scala集合过滤:移除被其他元素包含的字符串
给定初始集合:
val set1 = Set("hello world, this is scala new", "hello world, this is scala", "hello world, this is", "hello apple")
要移除所有被集合中其他元素包含的字符串,最终得到仅保留未被包含元素的集合,可以通过以下代码实现:
val set2 = set1.filter { str => !set1.exists(other => other != str && other.contains(str)) }
代码说明
filter方法用于筛选集合中符合条件的元素- 对每个元素
str,通过exists检查集合内是否存在另一个不同的元素包含它:other != str:避免元素自身和自己比较(字符串本身肯定包含自己)other.contains(str):判断其他元素是否包含当前字符串
- 当不存在这样的
other时,说明当前元素没有被任何其他元素包含,将其保留
执行后 set2 的结果为:
Set("hello world, this is scala new", "hello apple")
内容的提问来源于stack exchange,提问作者LizzyMM
相关产品推荐
相关产品推荐

