kotlin 是否有用于从两种不同类型的列表中获取公共数据的高阶函数?
Is there an high order function for kotlin for getting common data from two different type of list?
我遇到了与此 link 中所述相同的问题(但它在 swift 中)
我试过了:
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)
}
}
您可以使用 intersect 检索两个列表之间的共同项:
val l1 = listOf<Int>(1, 2, 3, 4, 5, 6, 7, 8, 9)
val l2 = listOf<Int>(1, 3, 5, 7, 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()
我遇到了与此 link 中所述相同的问题(但它在 swift 中)
我试过了:
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)
}
}
您可以使用 intersect 检索两个列表之间的共同项:
val l1 = listOf<Int>(1, 2, 3, 4, 5, 6, 7, 8, 9)
val l2 = listOf<Int>(1, 3, 5, 7, 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()