Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save thomasnield/d23ffb6677bdb4223f88f48e478265cf to your computer and use it in GitHub Desktop.

Select an option

Save thomasnield/d23ffb6677bdb4223f88f48e478265cf to your computer and use it in GitHub Desktop.
Kotlin Sequence Extensions for Google Guava Immutable Collections
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableListMultimap
import com.google.common.collect.ImmutableMap
import com.google.common.collect.ImmutableSet
fun <T> Sequence<T>.toImmutableList(): ImmutableList<T> {
val builder = ImmutableList.builder<T>()
forEach { builder.add(it) }
return builder.build()
}
fun <T> Sequence<T>.toImmutableSet(): ImmutableSet<T> {
val builder = ImmutableSet.builder<T>()
forEach { builder.add(it) }
return builder.build()
}
fun <T,K> Sequence<T>.toImmutableMap(keyMapper: (T) -> K): ImmutableMap<K,T> {
val builder = ImmutableMap.builder<K,T>()
forEach { builder.put(keyMapper(it), it) }
return builder.build()
}
fun <T,K,V> Sequence<T>.toImmutableMap(keyMapper: (T) -> K, valueMapper: (T) -> V): ImmutableMap<K,V> {
val builder = ImmutableMap.builder<K,V>()
forEach { builder.put(keyMapper(it), valueMapper(it)) }
return builder.build()
}
fun <T,K> Sequence<T>.toImmutableListMultimap(keyMapper: (T) -> K): ImmutableListMultimap<K,T> {
val builder = ImmutableListMultimap.builder<K,T>()
forEach { builder.put(keyMapper(it), it) }
return builder.build()
}
fun <T,K,V> Sequence<T>.toImmutableListMultimap(keyMapper: (T) -> K, valueMapper: (T) -> V): ImmutableListMultimap<K,V> {
val builder = ImmutableListMultimap.builder<K,V>()
forEach { builder.put(keyMapper(it), valueMapper(it)) }
return builder.build()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment