'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?



Solution 1:[1]

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;
   ...
}

Solution 2:[2]

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)) {
    // ...
}

Solution 3:[3]

The recommended way to iterate of a map is using an iterator or a for-each loop (which uses an iterator).

Converting your for each loop to a "normal" loop can work in your case, because you are using Integers as map keys:

for (int i = 0; i < mapDefect.size(); i++) {
  String value = mapDefect.get(i)
  // do something with value
}

But note that this only works if you are using map keys as you would use array/list indices (which makes the map useless). To use this kind of loop you have to use consecutive positive integers as map keys starting at 0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 micha