Java/Kotlin:通过类ID查找多个HashSet的交集 [英] Java/Kotlin: Finding the intersection of multiple HashSets by class ID

查看:240
本文介绍了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)

我已经从.csv文件中提取了一些数据到这种类型的结构中:

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

ArrayList<HashSet<Protein>>

因此,我有六个数组列表[每个csv 1个],每个包含一个散列集,其中包含数千个蛋白质结构.到目前为止,这是我尝试根据通用的Protein.id获取交集HashSet的方法:

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<Protein>>): HashSet<Protein> {

val intersectionSet = HashSet<Protein>(data[0])

for (i in 1..data.size) {
    intersectionSet.retainAll(data[i])
}
return intersectionSet
}

这将返回一个空列表,考虑到它试图与Protein对象相交并整体匹配每个条件,这是有道理的.

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

如何将data [i] .id称为交集标准?我对Kotlin和数据类很陌生:)

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

推荐答案

如果在Protein类中添加hashCodeequals函数的定义,则HashSet将能够适当地使用id字段检查路口.

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
}

此外,您可能还想将intersection函数中循环的范围更改为1..(data.size-1)而不是1..data.size,以避免越界.或者,您可以按以下方式编写功能:

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<Protein>>): HashSet<Protein> {
  return data.reduce { acc, it -> acc.apply { retainAll(it) } }
}

这篇关于Java/Kotlin:通过类ID查找多个HashSet的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆