-3

I have a list of items I am working through. I am looking for specific items in the initial list and would like to delete a found item from that list while traversing the list. I am traversing the list using for item : list

Is there a way of doing that without manipulating two lists?

  • 1
    Does this answer your question? [Remove elements from collection while iterating](https://stackoverflow.com/questions/10431981/remove-elements-from-collection-while-iterating) – OhleC Apr 27 '21 at 07:16
  • Does this answer your question? [Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop](https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – maloomeister Apr 27 '21 at 07:16
  • You would be best served by describing your problem in more detail. Using either `removeIf` or a stream is a more effective approach in most cases. – chrylis -cautiouslyoptimistic- Apr 27 '21 at 07:54
  • Please see http://idownvotedbecau.se/beingunresponsive – GhostCat Apr 27 '21 at 09:32

2 Answers2

0

I hope I get your question correctly but you could try:

Iterator<T> iter = list.iterator();
while (iter.hasNext()) {
    T t = iter.next();
    if (matchesCondition(t)) {
        iter.remove();
    }
}

But I have to say I don't get what you mean with "two lists" though. My answer might be completely irrelevant for you but then I need more information.

Christian
  • 1,437
  • 2
  • 8
  • 14
0

Let key be the value you need to check and delete from the list say inputList which is a list of integers.

for (int i=0; i<inputList.size(); i++) {
     int currentValue = inputList.get(i);
     if (currentValue == key) {
         inputList.remove(i); // this will remove the value at index i
         break;
     }
}

So say if we have a list, inputList = [1,2,3] and the key to be deleted is key=2, after iterating, 2 from the list will be removed and if we print the remaining elements, then inputList = [1,3] will be the final result and 2 will be removed.

Rohith V
  • 1,089
  • 1
  • 9
  • 23
  • Second line should be `inputList.get(i)` instead of `input.get(i)`. Furthermore, what happens when the list is say like `[1,2,2,3]` and I my "key" is still `2`? – maloomeister Apr 27 '21 at 07:35
  • Since he didnt tell about the duplicate values, I considered only unique values are present. – Rohith V Apr 27 '21 at 09:30