kotlin是否有一个高级函数可以从两种不同类型的列表中获取公共数据?

我有此链接中所述的相同问题(但很快) Getting common data from two different types of array

我尝试过:

 val list=ArrayList<Model>()
 val list1=ArrayList<Model1>()
 val hashMap=Hashmap<Int,Int>()
 for (i in list.indices) {
       val data = list1.filter { it.name == list[i].name }
        if (data.isnotEmpty()) {
        hashMap.put(data[0].id,list[i].id)
      }
    }
xiong_yingwen 回答:kotlin是否有一个高级函数可以从两种不同类型的列表中获取公共数据?

您可以使用intersect来检索两个列表之间的共同项目:

val l1 = listOf<Int>(1,2,3,4,5,6,7,8,9)
val l2 = listOf<Int>(1,9)
println(l1.intersect(l2))

要做的就是定义两个项目之间的相等性:

class A(val name: String) {
    override operator fun  equals(other: Any?): Boolean {
        if (other is B)
            return this.name == other.anotherFieldForName
        return false
    }
}

class B(val anotherFieldForName: String)


val l1 = listOf<A>(A("Bob"),A("Alice"),A("Margoulin"))
val l2 = listOf<B>(B("Bob"),B("Margoulin"))
println(l1.intersect(l2))
println(l2.intersect(l1))
,

编辑:根据下面的评论,这是一种无需对谓词进行两次迭代的方法:

val map = list.mapNotNull{el -> 
        list1.firstOrNull{el1 -> el.name == el1.name}?.let{el1 -> el.id to el1.id}
    }.toMap()
本文链接:https://www.f2er.com/3145058.html

大家都在问