Skip to content

Instantly share code, notes, and snippets.

@mreichelt
Created August 13, 2018 11:25
Show Gist options
  • Save mreichelt/a6e4b85c204962e4f1248324ec3bb418 to your computer and use it in GitHub Desktop.
Save mreichelt/a6e4b85c204962e4f1248324ec3bb418 to your computer and use it in GitHub Desktop.
Kotlin: Intersect maps with different value types on their keys
/**
* 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