Skip to content

Instantly share code, notes, and snippets.

@mohammadnr2817
Created November 19, 2022 14:11
Show Gist options
  • Save mohammadnr2817/b6b905f5ad4230cae4c7241f10b0655d to your computer and use it in GitHub Desktop.
Save mohammadnr2817/b6b905f5ad4230cae4c7241f10b0655d to your computer and use it in GitHub Desktop.
Kotlin intersect extension by selector
/**
* Returns a set containing all elements with keys returned by the given [selector] function
* that are both contained in this collection and the specified collection.
*
* The returned set preserves the element iteration order of the original collection.
*/
inline fun <T, K> Iterable<T>.intersectBy(other: Iterable<K>, selector: (T) -> K): Set<T> {
val list = ArrayList<T>()
for (e in this.toSet()) {
val key = selector(e)
if (other.contains(key))
list.add(e)
}
return list.toSet()
}
fun main() {
val list1 = listOf(Pair(1, "b"), Pair(2, "r"), Pair(3, "o"), Pair(4, "k"), Pair(5, "e"), Pair(6, "n"))
val list2 = listOf(1, 5)
val result = list1.intersectBy(list2) { it.first }
// result = [ Pair(1, "b"), Pair(5,"e") ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment