You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:50:29