我有一个这样的数据类:
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
}
As per another question I asked , 我现在有一个函数可以用蛋白质减少 HashSets 的 ArrayList
fun intersection(data: ArrayList<HashSet<Protein>>): HashSet<Protein> {
return data.reduce { acc, it -> acc.retainAll(it); acc }
}
我想要做的是获取原始 ArrayList 的一个子集并返回一个简化版本。所以我尝试这样做:
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)时,它减少得很好。当我通过第二个函数运行相同的数据时,它返回一个 map 错误,说找不到 key 。
我觉得这与 Protein 数据类的覆盖函数有关,但我找不到任何关于如何使用函数式编程来减少的信息......
最佳答案
我稍微简化了代码,得到了以下内容:
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)]
所以没有错误发生。能否请您提供您的测试代码?
关于java - Kotlin ArrayList<HashSet<data class>> .reduce 函数不适用于 ArrayList 的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49975670/