Kotlin ArrayList<HashSet<data class>> .reduce 函数不适用于 ArrayList 的子集

Kotlin ArrayList<HashSet<data class>> .reduce function not working with subset of ArrayList

我有这样的数据class:

data class Protein(val id: String, val score: Double, val molw: Double, val spc: Int) {
    override fun hashCode() = id.hashCode()
    override fun equals(other: Any?) = other?.let { id == (it as Protein).id } ?: false
}

,我现在有一个函数可以用蛋白质减少 HashSet 的 ArrayList

fun intersection(data: ArrayList<HashSet<Protein>>): HashSet<Protein> {
  return data.reduce { acc, it -> acc.retainAll(it); acc }
}

我想要做的是获取原始 ArrayList 的子集和 return 简化版本。所以我试着这样做:

fun intersection(data: ArrayList<HashSet<Protein>>, combination: List<Int>): HashSet<Protein> {
val newdata = ArrayList<HashSet<Protein>>()
for (entry in combination) {
    newdata.add(data[entry-1]) }
return newdata.reduce { acc, it -> acc.retainAll(it); acc } }

组合告诉函数要从数据 ArrayList 中获取哪些条目(例如 1、2、4)。 newdata ArrayList 的大小将始终为 3(也检查了这一点)。

当我运行原始数据(ArrayList of 6)通过第一个交集函数时,它减少就好了。当我通过第二个函数 运行 相同的数据时,它 return 是一个映射错误,说找不到密钥。

我感觉这与蛋白质数据的覆盖函数有关 class,但我找不到任何有关如何使用函数式编程来减少的信息...

我稍微简化了代码,得到了以下内容:

fun intersection(data: List<HashSet<Protein>>) =
    data.reduce { acc, it -> acc.apply { retainAll(it) } }

fun intersection(data: List<HashSet<Protein>>, combination: List<Int>) =
    intersection(combination.map { data[it - 1] })

我能够通过以下方式获得预期的结果:

val s1 = hashSetOf(Protein("1",2.0, 2.0,1), Protein("2",2.0, 2.0,1))
val s2 = hashSetOf(Protein("3",2.0, 2.0,1), Protein("2",2.0, 2.0,1))
val s3 = hashSetOf(Protein("3",2.0, 2.0,1), Protein("4",2.0, 2.0,1))
println(intersection(listOf(s1,s2,s3), listOf(1,2))) //[Protein(id=2, score=2.0, molw=2.0, spc=1)]

所以没有发生错误。能否请您提供您的测试代码?