How to limit the number of iterations through the List
Question
How I can limit the result of an iterator over my List?
try {
ArrayList<CalanderQueryOutput> results = new ArrayList<CalanderQueryOutput>();
List<?> eventsToday = (List<?>) filter.filter(calendar.getComponents(Component.VEVENT));
CalanderQueryOutput caldavOutput = new CalanderQueryOutput();
for (Iterator<?> i = eventsToday.iterator(); i.hasNext();) {
}
results.add(caldavOutput);
}
I want list only maximum ten results
La solution
In the loop , use a counter and check it like this:
if(counter < 10) results.add(caldavOutput);
.....
......
counter++;
Autres conseils
You can add a counter and break;
the loop when the counter reaches a certain value.
Before the loop:
int counter = 1;
in the loop:
if(counter >= 10)
break;
/* loop code */
counter++;
Just do this:
...
for (Object event : eventsToday.subList(0, Math.min(9, eventsToday.size() - 1))) {
// do something with "event"
}
...
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow