org.jetbrains.kotlin.utils.collections.kt Maven / Gradle / Ivy
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.utils
import java.util.ArrayList
import java.util.HashMap
import java.util.HashSet
import java.util.LinkedHashMap
public fun Sequence.valuesToMap(key: (V) -> K): Map {
val map = LinkedHashMap()
for (v in this) {
map[key(v)] = v
}
return map
}
public fun Sequence.keysToMap(value: (K) -> V): Map {
val map = LinkedHashMap()
for (k in this) {
map[k] = value(k)
}
return map
}
public fun Sequence.keysToMapExceptNulls(value: (K) -> V?): Map {
val map = LinkedHashMap()
for (k in this) {
val v = value(k)
if (v != null) {
map[k] = v
}
}
return map
}
public fun Iterable.valuesToMap(key: (V) -> K): Map {
val map = LinkedHashMap()
for (v in this) {
map[key(v)] = v
}
return map
}
public fun Iterable.keysToMap(value: (K) -> V): Map {
val map = LinkedHashMap()
for (k in this) {
map[k] = value(k)
}
return map
}
public fun Iterable.keysToMapExceptNulls(value: (K) -> V?): Map {
val map = LinkedHashMap()
for (k in this) {
val v = value(k)
if (v != null) {
map[k] = v
}
}
return map
}
public fun Iterable.mapToIndex(): Map {
val map = LinkedHashMap()
for ((index, k) in this.withIndex()) {
map[k] = index
}
return map
}
public inline fun > C.ifEmpty(body: () -> C): C = if (isEmpty()) body() else this
public fun emptyOrSingletonList(item: T?): List = if (item == null) listOf() else listOf(item)
public fun MutableCollection.addIfNotNull(t: T?) {
if (t != null) add(t)
}
public fun newHashMapWithExpectedSize(expectedSize: Int): HashMap {
return HashMap(if (expectedSize < 3) 3 else expectedSize + expectedSize / 3 + 1)
}
public fun newHashSetWithExpectedSize(expectedSize: Int): HashSet {
return HashSet(if (expectedSize < 3) 3 else expectedSize + expectedSize / 3 + 1)
}
public fun Collection.toReadOnlyList(): List =
when (size()) {
0 -> emptyList()
1 -> listOf(first())
else -> ArrayList(this)
}
public fun T?.singletonOrEmptyList(): List =
if (this != null) listOf(this) else emptyList()
public fun MutableList.removeLast(condition: (T) -> Boolean): T? {
val index = indexOfLast(condition)
return if (index >= 0) removeAt(index) else null
}