0

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

Alex K
  • 22,315
  • 19
  • 108
  • 236

3 Answers3

1

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++;
Mesop
  • 5,187
  • 4
  • 25
  • 42
1

Just do this:

...
for (Object event : eventsToday.subList(0, Math.min(9, eventsToday.size() - 1))) {
    // do something with "event"
}
...
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

In the loop , use a counter and check it like this:

if(counter < 10) results.add(caldavOutput);
.....
......
counter++;
UVM
  • 9,776
  • 6
  • 41
  • 66