Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (46k 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

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 13, 2019 in Java by Nigam (4k points)
0 votes
1 answer

Browse Categories

...