0 votes
1 view
in Java by (3.5k points)

AFAIK, there are two approaches:

Iterate over a copy of the collection

Use the iterator of the actual collection

For instance,

List<Foo> fooListCopy = new ArrayList<Foo>(fooList);

for(Foo foo : fooListCopy){

    // modify actual fooList

}

and

Iterator<Foo> itr = fooList.iterator();

while(itr.hasNext()){

    // modify actual fooList using itr.remove()

}

Are there any reasons to prefer one approach over the other (e.g. preferring the first approach for the simple reason of readability)?

1 Answer

0 votes
by (46.1k points)

In Java 8, there is another approach. Collection#removeIf

eg:

List<Integer> list = new ArrayList<>();

list.add(1);

list.add(2);

list.add(3);

list.removeIf(i -> i > 2);

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...