简体   繁体   中英

Remove element n from Java List dependent on n + 1 element

I want to achieve the following but with a List instead of an array (Remove some element based on comparisons between a neighboring element in the array)

Interval: {
  start,
  end,
  priority;
}

    Interval[] intervals = someIntervalsSortedByStartTime();//[(1,5), (4, 5)]
    for(int i=0; i<intervals.length-1; i++){
    if(intervals[i] == null) continue;
    if((intervals[i].end > intervals[i+1].start) ){
        if(intervals[i].priority < intervals[i+1].priority){
          intervals[i] = null //i.e. have the element removed.
        }else if(intervals[i].priority > intervals[i+1].priority{
          itervals[i+1] = null;
        }else{
         throw new WTFException();
        }
    }
}

I know With collection things are a bit different for one we need to use Iterator, ListIterator, Apache collections Iteration, or Google Collections iterator. to remove an item from the List.

ListIterator, Apache, and Google have .previous or .peek methods that can some what allow for the "look ahead" functionality thats shown in the for loop example. However if you use them in addition to .remove() if .previous or .peek was last called before .remove() the previous item will be removed and there isnt a way to specify .remove(index) you would have to call .next().next in some cases and manage getting back to where you want the iterator to be after every iteration.

Steams wont work in this case either as we cant filter based on other elements in the List ie we cant get a "next" in steams.

I also wanted to avoid making a temporary copy of the data and deleting the data afterwards.

What would be the best approach of achieving the desired functionality?

You can use a List like an array, you create a loop and use the methods get(int index) and remove(int index) to access/remove Elements from the list. You just have to keep track of the indexes when you delete elements. To avoid this, you can start at the end of the list and work to the beginning:

for (int i=intervals.length-1; i>=0; i--)

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