代码之家  ›  专栏  ›  技术社区  ›  PeptideWitch

Kotlin ArrayList<哈希集<数据类>>。reduce函数不使用ArrayList的子集

  •  3
  • PeptideWitch  · 技术社区  · 8 年前

    我有这样一个数据类:

    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 ,我现在有了一个函数,可以减少包含蛋白质的哈希集数组列表

    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 } }
    

    组合告诉函数从数据数组列表中获取哪些条目(例如1、2、4)。newdata ArrayList的大小始终为3(也选中了此选项)。

    当我通过第一个交集函数运行原始数据(ArrayList为6)时,它会很好地减少。当我通过第二个函数运行相同的数据时,它返回一个映射错误,表示找不到键。

    我有一种感觉,这与蛋白质数据类的覆盖函数有关,但我找不到任何关于如何使用函数编程来减少。。。

    1 回复  |  直到 8 年前
        1
  •  2
  •   s1m0nw1    8 年前

    我对代码进行了一些简化,得到了以下内容:

    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)]
    

    因此没有发生错误。你能提供你的测试代码吗?