is there a list type where you can insert into the...
# announcements
t
is there a list type where you can insert into the middle? either before or after a element, or at an index? any of the above?
d
t
that doesn't look like it does an insert. what am I missing?
d
it does insert... the statement
list.add(1, 2)
means insert element 2 at index 1... probably because it's a lot of numbers so its confusing
i changed the example with string...
t
add()
appends to the end. I want to insert into the middle of an already existing list (mutable obviously)
d
can you read the code fully?
does this code not visible?
t
It is not. The link I now see is adding INTs not strings
d
try this one then: https://pl.kotl.in/fi7mD-JmD
t
still no strings.. but it's ok. I get the idea. I thought add() and a index replaced it, but in inserts. that's what I was looking for.
ah drat. there is no findIndexed....
d
you mean, retrieving an item at specific index? or find an index of an element?
t
find a element and know it's index.
d
there is an indexOf method
t
I assume that needs to search the list again?
d
yes... or i might not catch what you're trying to do
t
indexOf will work. it's just gonna be slower.
so, a bunch of the other list functions have "...Indexed" version. filterIndex, etc. It gives you the element and the index.
find doesn't.
I'm trying to insert into an already sorted list.
with as best performance as I can get. it's a latency sensitive app, and this operation will be done alot.
d
well if your list is alredy sorted, you can try binarysearch
you can test the indexof, sometimes this kind of microoptimisation might not even worth... of course depending on how many items you already have in the list
t
I'm not trying to find a element in the list. I'm trying to insert a new element into the list.
or I could zip the list w/ the index. but that's kinda slow as well.
it's worth it. I've written this in other languages that have linked list implementations and it makes a big difference. I'm just trying it in kotlin.
or I can just write it as a tailrec function w/ a iterator and keep the index myself. might be better anyway
d
sure
e
maybe you want MutableListIterator
t
yeah, that's totally what I want.
t
Just to add a completely different thought: If you don't need duplicates in your list, you could also use a SortedSet (usually TreeSet, at least if you're on JVM) that takes care of sorting for you and is optimized for doing so.
☝️ 1