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?
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.
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.
To convert a for loop to while loop we need to simply add the initialization statement before the while loop.
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;
...
}
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)) {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With