Replicator Eclipse Iterator / while toeach

Does anyone know if there is an easy way to refactor code using foreach to iterate through the collection instead of the while / Iterator combination?

Example:

I have:

Iterator<MyObject> iterator = list.iterator(); while (iterator.hasNext()) { MyObject myObject = iterator.next(); // do stuff } 

I want too:

 for (MyObject myObject : list) { // do stuff } 

And yes, I understand that I won’t get any performance improvements. I just want it to be less detailed and because I like it :)

+5
source share
1 answer

Assuming all cases of iterative code are similar to your example, try using a search and replace with the following regular expression.

Search:

 Iterator<([a-zA-Z0-9_]{1,})> [a-zA-Z0-9_]{1,} = ([a-zA-Z0-9_]{1,})\.iterator\(\);\R[\t]{1,}while \(iterator\.hasNext\(\)\) \{\R[\t]{1,}[a-zA-Z0-9_]{1,} ([a-zA-Z0-9_]{1,}) = iterator\.next\(\); 

Replace:

 for($1 $3 : $2) { 
0
source

Source: https://habr.com/ru/post/1247460/


All Articles