All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dankito.utils.extensions.CollectionsExtensions.kt Maven / Gradle / Ivy

There is a newer version: 1.0.20
Show newest version
package net.dankito.utils.extensions

import java.text.Collator
import java.util.*


class CollectionsExtensions {
    companion object {
        val collator = Collator.getInstance()

        init {
            collator.strength = Collator.IDENTICAL
        }
    }
}


fun  Collection.containsAny(otherCollection: Collection): Boolean {
    for (otherItem in otherCollection) {
        if (this.contains(otherItem)) {
            return true
        }
    }

    return false
}

fun  Collection.containsExactly(vararg items: T): Boolean {
    return containsExactly(items.toList())
}

fun  Collection.containsExactly(otherCollection: Collection): Boolean {
    if (this.size != otherCollection.size) {
        return false
    }

    for (otherItem in otherCollection) {
        if (this.contains(otherItem) == false) {
            return false
        }
    }

    return true
}


/**
 * Standard sortedBy() function doesn't take characters like German Umlaute into consideration (so that e.g. Ärzte is ordered after Zucker)
 * -> use a Collator with at least strength of Collator.SECONDARY
 */
fun  Iterable.sortedByStrings(selector: (T) -> String): List {
    return sortedWith(kotlin.Comparator { o1, o2 -> CollectionsExtensions.collator.compare(selector(o1), selector(o2)) })
}


fun  Collection.didCollectionChange(collectionToCompareTo: Collection): Boolean {
    if(this.size != collectionToCompareTo.size) {
        return true
    }

    val copy = ArrayList(collectionToCompareTo)
    copy.removeAll(this)
    return copy.size > 0
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy