Created
November 19, 2022 14:11
-
-
Save mohammadnr2817/b6b905f5ad4230cae4c7241f10b0655d to your computer and use it in GitHub Desktop.
Kotlin intersect extension by selector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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