Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For each to For Loop Conversion

May I know how do I convert the following for each loop to a normal for loop?

for (SortedMap.Entry<Integer, String> entry : mapDefect.entrySet())

I have a count variable as the starting point and the end of the map as the end point. So accordingly how may I convert it into a normal for loop?

like image 252
Pramod Setlur Avatar asked Dec 19 '12 10:12

Pramod Setlur


People also ask

Is for each loop better than for loop?

Deductions. This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.

What is foreach loop with example?

In this program, foreach loop is used to traverse through a collection. Traversing a collection is similar to traversing through an array. The first element of collection is selected on the first iteration, second element on second iteration and so on till the last element.

Can we convert for loop to while loop?

To convert a for loop to while loop we need to simply add the initialization statement before the while loop.


2 Answers

You say the task is to skip the first count elements, and process the rest.

This can be done with either a "for" loop, or a "for each" loop. In this case, I'd keep this as a "for each" loop:

int i = 0;
for (SortedMap.Entry<Integer, String> entry : mapDefect.entrySet()) {
   if (i++ < count) continue;
   ...
}
like image 26
NPE Avatar answered Oct 08 '22 03:10

NPE


Section 14.14.2 of the JLS gives the translation. In this case, it would be roughly:

for (Iterator<SortedMap.Entry<Integer, String>> iterator
         = mapDefect.entrySet().iterator();
     iterator.hasNext(); )
{
    SortedMap.Entry<Integer, String> entry = iterator.next();
    // ...
}

Alternatively, use Guava's Iterables class to take a section of the sorted set:

Iterable<SortedMap.Entry<Integer, String>> section = Iterables.limit(
    Iterables.skip(mapDefect.entrySet(), start), end - start);
for (SortedMap.Entry<Integer, String> entry : section) {
    // ...
}

Or if it's just from count (with the clarifying comment):

for (SortedMap.Entry<Integer, String> entry :
         Iterables.skip(mapDefect.entrySet(), count)) {
    // ...
}
like image 132
Jon Skeet Avatar answered Oct 08 '22 01:10

Jon Skeet