Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Created May 28, 2022 07:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rommansabbir/a1027f44fd2004b063f97e09f3a7d8cc to your computer and use it in GitHub Desktop.
Save rommansabbir/a1027f44fd2004b063f97e09f3a7d8cc to your computer and use it in GitHub Desktop.
Set,List to HashMap (Kotlin)
/*Transform a *Set* into a *HashMap**/
suspend fun <T> Set<T>.toHashMap(): HashMap<Int, T> = withContext(Dispatchers.IO) {
val hashMap: HashMap<Int, T> = HashMap()
var index = 0
this@toHashMap.forEach {
if (hashMap.isEmpty()) hashMap[0] = it else index = hashMap.size; hashMap[index++] = it
}
hashMap
}
/*Transform a *List* into a *HashMap**/
suspend fun <T> List<T>.toHashMap(): HashMap<Int, T> = withContext(Dispatchers.IO) {
val hashMap: HashMap<Int, T> = HashMap()
var index = 0
this@toHashMap.forEach {
if (hashMap.isEmpty()) hashMap[0] = it else index = hashMap.size; hashMap[index++] = it
}
hashMap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment