如何在 Kotlin 中判断两个对象列表是否相等

huangapple go评论85阅读模式
英文:

how to find of 2 lists of objects are equal in kotlin

问题

我有两个数据列表:

data class PatientData(var patientID: String, var patientName: String, var patientPhone: String)

var list1: List<PatientData>? = null
var list2: List<PatientData>? = null

我需要判断list1是否与list2重复。一种确定方法是根据patientID进行匹配。

我尝试过不同的方法,如使用zip和contentEquals,但都没有成功。

英文:

I have 2 lists of data:

data class PatientData(var patientID: String, var patientName:String, var patientPhone:String)

var list1: List&lt;PatientData&gt;?=null
var list2: List&lt;PatientData&gt;?=null

I need to determine if list1 is a duplicate of list2. One way of determining this is matching on patientID.

I have tried different ways such as zip and contentEquals but it did not work.

答案1

得分: 0

你的数据类在大多数比较工作中都可以直接使用,所以只需要进行一些集合比较。

就像Animesh所说,你可以进行大小检查以及containsAll操作(如果你知道它们的大小相同,只需单向执行containsAll检查)

if (list1.size == list2.size && list1.containsAll(list2))

你可以对列表进行排序,然后直接比较它们(由于你的类没有实现Comparable接口,我们需要自己处理,假设patientId是一个唯一的值)

if (list1.sortedBy { it.patientID } == list2.sortedBy { it.patientID })

或者你可能实际上想要使用Set,如果你不想要重复的PatientData对象 - 这将使你能够执行像并集和交集这样的集合操作,但是为了比较两个集合是否相等,它们需要包含相同的项目集合

if (set1 == set2)
英文:

Your data class is doing most of the comparison work for you out of the box, so it's just a case of doing some collection comparisons.

Like Animesh says, you can do a size check and a containsAll (if you know they're the same size you only need to do the containsAll check one way)

if (list1.size == list2.size &amp;&amp; list1.containsAll(list2))

You can sort the lists and then directly compare them (since your classes don't implement Comparable we'll have to do it ourselves, patientId is a good choice assuming it's a unique value)

if (list1.sortedBy { it.patientID } == list2.sortedBy { patientID })

Or you might actually want to use a Set for this, if you don't want duplicate PatientData objects anyway - that will let you do nice set properties like unions and intersections, but for comparison purposes two sets are equal if they contain the same collection of items

if (set1 == set2)

huangapple
  • 本文由 发表于 2020年9月29日 23:44:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64123063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定