Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Move object to front of LinkedList

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

like image 202
btd Avatar asked Mar 30 '14 19:03

btd


1 Answers

Iterator it = list.iterator();
while (it.hasNext()) {
    Object thing = it.next();
    if (ThisIsTheObjectWeAreLookingFor(thing)) {
        it.remove();
        list.addFirst(thing);
        return thing;
    }
}
like image 114
leventov Avatar answered Oct 21 '22 13:10

leventov