Java - Move object to front of LinkedList

data-structures, java, linked-list

Solution

Iterator it = list.iterator();
while (it.hasNext()) {
    Object thing = it.next();
    if (ThisIsTheObjectWeAreLookingFor(thing)) {
        it.remove();
        list.addFirst(thing);
        return thing;
    }
}

Problem

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.)

Original source

Related problems