给出两节课:
data class Foo(val id: Int, val foo: String)
data class Bar(val id: Int, val fId: Int, val bar: String)
以及每一项的项目列表:
val foos: List<Foo>
val bars: List<Bar>
如果Foo中的id
与Bar中的fId
匹配,我想将foos
的列表与bars
相交.
现在我使用的是:
val actual = foos.filter {
bars.any { b -> b.fId == it.id }
}
因为我经常使用这个模式,这基本上只是一个交集,我以为Kotlin中有一个std方法,但找不到.我希望:
val actual = foos.intersect(bars, { (f, b) -> b.fId == f.id })
因为我找不到任何东西,所以我添加了一个扩展方法:
fun<T, U> List<T>.intersect(list2: List<U>, p: (a: T, b: U) -> Boolean): List<T> =
this.filter { list2.any { other -> p(it, other) } }
在对此进行大量引用之前,我想仔细判断一下我正在寻找的东西是否有不同的名称,以及我是否在寻找错误的方法.