Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the replacement of For-Each loop for filtering?

Tags:

java

foreach

list

Though for-each loop has many advantages but the problem is ,it doesn't work when you want to Filter(Filtering means removing element from List) a List,Can you please any replacement as even traversing through Index is not a good option..

like image 870
Ashish Agarwal Avatar asked Dec 07 '25 08:12

Ashish Agarwal


1 Answers

What do you mean by "filtering"? Removing certain elements from a list? If so, you can use an iterator:

for(Iterator<MyElement> it = list.iterator(); it.hasNext(); ) {
    MyElement element = it.next();
    if (some condition) {
      it.remove();
    }
}

Update (based on comments):

Consider the following example to illustrate how iterator works. Let's say we have a list that contains 'A's and 'B's:

A A B B A

We want to remove all those pesky Bs. So, using the above loop, the code will work as follows:

  1. hasNext()? Yes. next(). element points to 1st A.
  2. hasNext()? Yes. next(). element points to 2nd A.
  3. hasNext()? Yes. next(). element points to 1st B. remove(). iterator counter does NOT change, it still points to a place where B was (technically that's not entirely correct but logically that's how it works). If you were to call remove() again now, you'd get an exception (because list element is no longer there).
  4. hasNext()? Yes. next(). element points to 2nd B. The rest is the same as #3
  5. hasNext()? Yes. next(). element points to 3rd A.
  6. hasNext()? No, we're done. List now has 3 elements.

Update #2: remove() operation is indeed optional on iterator - but only because it is optional on an underlying collection. The bottom line here is - if your collection supports it (and all collections in Java Collection Framework do), so will the iterator. If your collection doesn't support it, you're out of luck anyway.

like image 152
ChssPly76 Avatar answered Dec 09 '25 22:12

ChssPly76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!