Home > Blockchain >  Kotlin - MutableList that does not allow duplicate Object
Kotlin - MutableList that does not allow duplicate Object

Time:02-11

Is there idiomatic expression or extension sample for a MutableList and List that does not allow duplicate object or if possible, update the existing object in list if duplicate? Just like how HashMap works? I am not sure if using .map {} is the most efficient way of doing it.

Note: Still need having a correct index.

CodePudding user response:

The Set interface allows only one of each unique item, where "unique" is in terms of the class's equals function.

The Set interface does not guarantee fixed order of elements as part of its contract, but all the Kotlin standard library functions that create Sets create Sets that do maintain order of elements (the order they were added to the set).

You can iterate a Set with index using forEachIndexed or for((index, item) in set.withIndex()).

There's no indexed access operator for sets, but you could create an extension that enables it. Note that since Sets with order are backed by linked wrappers instead of an array, it is inefficient to access elements by index, because it has to iterate up to that index to retrieve the value.

operator fun <T> Set<T>.get(index: Int) = asSequence().drop(index).first()

If you have a MutableSet, you cannot insert elements at a specific index. You would have to clear it and reinsert everything in the order you want.

CodePudding user response:

You can have a solution from here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list/set.html

  • Related