Created
August 13, 2018 11:25
-
-
Save mreichelt/a6e4b85c204962e4f1248324ec3bb418 to your computer and use it in GitHub Desktop.
Kotlin: Intersect maps with different value types on their keys
This file contains hidden or 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
/** | |
* Intersect two maps with same keys, but different data types. Preserves the order of the first map. | |
* Returns a list of the combined type provided by the transformation. | |
*/ | |
inline fun <Key, Value1, Value2, T> Map<Key, Value1>.intersectWith( | |
other: Map<Key, Value2>, | |
transformationFunction: (Value1, Value2) -> T): List<T> { | |
return flatMap { oldEntry -> | |
other.filterKeys { it == oldEntry.key } | |
.map { transformationFunction(oldEntry.value, it.value) } | |
} | |
} | |
/** | |
* Intersect two maps with same keys, but different data types. Preserves the order of the first map. | |
* Returns a list of pairs of both value types. | |
*/ | |
fun <Key, Value1, Value2> Map<Key, Value1>.intersectWith(other: Map<Key, Value2>): List<Pair<Value1, Value2>> { | |
return flatMap { oldEntry -> | |
other.filterKeys { it == oldEntry.key } | |
.map { Pair(oldEntry.value, it.value) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment