'Repeatedly reading and returning chunks of data from enumeration

I have a Java function that looks like:

public List<File> myFunction(){
     Enumeration<File> myFiles = enumFiles();
     int i = 0;
      while(myFiles.hasMoreElements() && i < 50){
          // i will add the element to an arraylist here
           i++;
      }

     return "100 files from myFiles"
}

where enumFiles() returns Enumeration of files. The list of files can be thousands or millions. I am using the hasMoreElements() and nextElement() to read the first 50 files.

What I want is to be able to let say return the next 100 files whenever myFunction() is called. Each 100 files will start where it ended previously until there are no more elements in myFiles.

I have searched but did not find an answer. I need a little direction on how to do it.



Solution 1:[1]

You probably want an iterator of your own.

class LimitedIterator<T> implements Iterator<List<T>> {
     private int chunkSize;
     private Iterator<T> baseIterator;
     public LimitedIterator(Iterator<T> base, int size) {
         baseIterator = base;
         chunkSize = size;
     }
     public boolean hasNext() {
         return baseIterator.hasNext();
     }
     public List<T> next() {
         List<T> result = new ArrayList<>(chunkSize);
         for (int i = 0; i < chunkSize && baseIterator.hasNext(); i++) {
             result.add(baseIterator.next();
         }
         return result;
     }
}

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 daniu