Skip to content

Instantly share code, notes, and snippets.

@geoand
Created June 6, 2016 09:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geoand/0e4bcba698c69ae4a4f8fa416bdd53fd to your computer and use it in GitHub Desktop.
Save geoand/0e4bcba698c69ae4a4f8fa416bdd53fd to your computer and use it in GitHub Desktop.
fun <T, M> Iterable<T>.countBy(transformer: (T) -> M) : Map<M, Int> {
val emptyMap = mapOf<M, Int>()
return this.fold(emptyMap) {accumulator, item ->
val transformedItem = transformer(item)
accumulator + Pair(transformedItem, accumulator.getOrElse(transformedItem, {0}) + 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment