简体   繁体   中英

Java List<T> remove consecutive equal elements

I have a List<Log> , where Log is a Java Class with various attributes.

I need to delete two consecutive Log objects if they are equal. I defined that two logs are equal if their log_message are equal and their timestamp are very close to each other.

One idea is to go through every log of the list and check if the current is equal to the next. If this is true, then i need to delete the current object from the list and move on.

I need to maintain the order of List<Log> (i can sort the list, and then ordenate again by decreasing timestamp if necessary). The List<Log> is already ordered by decreasing timestamp.

I tried to do something like this:

int i = 0;
ListIterator<T> it = list_tmp.listIterator(); // list_tmp is the List<Log>
while(it.hasNext()){
    current = list_tmp.get(i);
    next = list_tmp.get(i+1);
    if(current.getLogMessage().equals(next.getLogMessage())){
        list_tmp.remove(current);
    }
    i++;
}

But i get an error of index out of range.

Am I thinking this wrong? Is there another way to do it better?

You already have an iterator - your should use it, and not the indexes:

Log prev = null;
Log current = it.next();
while (it.hasNext()) {
    prev = current;
    current = it.next();
    if (current.getLogMessage().equals(next.getLogMessage())) {
        it.remove();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM