net.dankito.utils.extensions.CollectionsExtensions.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-utils Show documentation
Show all versions of java-utils Show documentation
Some basic utils needed in many projects
The 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
}