英文:
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<PatientData>?=null
var list2: List<PatientData>?=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 && 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论