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

Kotlin中如何求两个列表的交集并保存为字符串集合?

在Kotlin中计算两个不同类型列表的交集并转为字符串集合

你的两个列表类型不同(MutableList<JSONArray> 和 MutableList<MutableList<String>>),需先统一转换为字符串集合,再计算交集。

实现步骤

  • 提取list中所有JSONArray的字符串元素,合并为字符串集合
  • 平铺otherList的嵌套结构,提取所有字符串元素并转为集合
  • 调用集合的交集方法得到结果

代码示例

import org.json.JSONArray

val list: MutableList<JSONArray> = Arrays.asList(requestedFields)
val otherList: MutableList<MutableList<String>> = Arrays.asList(requiredFields)

// 转换JSONArray列表为字符串集合
val requestedStrSet = list.flatMap { jsonArr ->
    (0 until jsonArr.length()).map { jsonArr.getString(it) }
}.toSet()

// 转换嵌套字符串列表为字符串集合
val requiredStrSet = otherList.flatMap { it }.toSet()

// 计算交集,结果为字符串集合
val intersection: Set<String> = requestedStrSet.intersect(requiredStrSet)

// 若需可变集合,可进一步转换
val mutableIntersection: MutableSet<String> = intersection.toMutableSet()

关键说明

  • flatMap:用于将嵌套结构(JSONArray或子列表)平铺为单一元素序列
  • toSet():去重并转换为集合,便于调用集合的交集方法
  • intersect:直接返回两个集合的交集,结果为Set<String>类型

内容的提问来源于stack exchange,提问作者mobi_dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:45:33