I'm iterating through a list of objects in a LinkedList, searching for the first one that meets some condition. Once found, I want to move it to the front of the list to reduce average time spent searching for commonly-searched-for objects in the list.
Psuedocode example of what I'm trying to do:
for(Object thing:list){
if(ThisIsTheObjectWeAreLookingFor(thing)){
list.RemoveCurrentLinkedListNode();
list.addFirst(thing);
return thing;
}
}
I know I could use the remove(Object) or remove(index) methods, but that would be slower. Substantially so, depending on the number of elements in the list. (Since the methods would have to iterate through the list a second time.)
Iterator it = list.iterator();
while (it.hasNext()) {
Object thing = it.next();
if (ThisIsTheObjectWeAreLookingFor(thing)) {
it.remove();
list.addFirst(thing);
return thing;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With