
tech.harmonysoft.oss.common.collection.CollectionInitializer.kt Maven / Gradle / Ivy
package tech.harmonysoft.oss.common.collection
import java.util.*
import java.util.concurrent.ConcurrentHashMap
/**
* Quite often many lambda objects are generated during frequent calls like [getOrPut]:
*
* ```
* class MyClass {
* private val cache = mutableMapOf>()
*
* fun service(key: String) {
* cache.getOrPut(key) { Stack() }
* }
* }
* ```
*
* That way it's more effective pre-defining initializers and use them like below - by doing that we avoie
* unnecessary lambda objects construction:
*
* ```
* cache.getOrPut(key, CollectionInitializer.stack())
* ```
*/
@Suppress("UNCHECKED_CAST")
object CollectionInitializer {
private val STACK: () -> Stack = { Stack() }
private val MUTABLE_LIST: () -> MutableList = { mutableListOf() }
private val MUTABLE_SET: () -> MutableSet = { mutableSetOf() }
private val MUTABLE_MAP: () -> MutableMap = { mutableMapOf() }
private val CONCURRENT_HASH_SET: () -> MutableSet = { Collections.newSetFromMap(ConcurrentHashMap()) }
private val CONCURRENT_HASH_MAP: () -> ConcurrentHashMap = { ConcurrentHashMap() }
fun stack(): () -> Stack = STACK as () -> Stack
fun mutableList(): () -> MutableList = MUTABLE_LIST as () -> MutableList
fun mutableSet(): () -> MutableSet = MUTABLE_SET as () -> MutableSet
fun mutableMap(): () -> MutableMap = MUTABLE_MAP as () -> MutableMap
fun concurrentHashSet(): () -> MutableSet = CONCURRENT_HASH_SET as () -> MutableSet
fun concurrentHashMap(): () -> ConcurrentHashMap = CONCURRENT_HASH_MAP as () -> ConcurrentHashMap
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy