java查询多个id,Java / Kotlin:通过类ID查找多个HashSet的交集

I'm having trouble finding the intersection of an Array of Hashed Sets that contain a data Class (where I want to intersect by identifier):

class Protein(val id: String, val score: Double, val molw: Double, val spc: Int)

I've pulled in some data from a .csv file into this type of structure:

ArrayList>

So I have six array lists [1 for each csv], each containing one hashed set that contains thousands of Protein structures. Here's what I've tried so far to get an intersection HashSet based off of common Protein.id:

fun intersection(data: ArrayList>): HashSet {

val intersectionSet = HashSet(data[0])

for (i in 1..data.size) {

intersectionSet.retainAll(data[i])

}

return intersectionSet

}

This returns an empty list, which makes sense given that it's trying to intersect Protein objects and match each criteria as a whole.

How do I call data[i].id as my intersection criteria? I'm fairly new to Kotlin and data classes :)

解决方案

If you add definitions for the hashCode and equals function in the Protein class as follows, then the HashSet will be able to appropriately check the intersection using the id field.

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

}

Also you probably want to change the range in your loop within the intersection function to be 1..(data.size-1) instead of 1..data.size to avoid going out of bounds. Alternatively you could write it functionally as follows:

fun intersection(data: ArrayList>): HashSet {

return data.reduce { acc, it -> acc.apply { retainAll(it) } }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值