Mat*_*son 7 collections set kotlin
是否有 Kotlin stdlib 函数可以查找两个集合之间的对称差异?因此,给定两个集合[1, 2, 3],[1, 3, 5]对称差为[2, 5]。
我已经编写了这个扩展函数,它运行良好,但感觉像是集合框架中应该已经存在的操作。
fun <T> Set<T>.symmetricDifference(other: Set<T>): Set<T> {
val mine = this subtract other
val theirs = other subtract this
return mine union theirs
}
Run Code Online (Sandbox Code Playgroud)
编辑:在java中获得两个集合之间的对称差异的最佳方法是什么?建议 Guava 或 ApacheCommons,但我想知道 Kotlin 的 stdlib 是否支持这一点。
微小变化:
infix fun <T> Set<T>.xor(that: Set<T>): Set<T> = (this - that) + (that - this)
Run Code Online (Sandbox Code Playgroud)
用法:
a xor b
Run Code Online (Sandbox Code Playgroud)
为了减少 GC 开销,必须使用带有自定义迭代器的更复杂的类似 Guava 的 解决方案。
| 归档时间: |
|
| 查看次数: |
3043 次 |
| 最近记录: |