Groovy.collect item limited

Is there a way to use the groovy method .collect, but only up to a specific index in the source array?

For example, if your original iterator was 1 million long and your limit was 100, you would get an array of 100 elements.

+5
source share
3 answers

If you use any data structure that implements java.util.List, you can do collection.subList(0, 100)on it. Where 0 is the start index and 100 is the end. After that, you will transfer the new collection to collect().

Here is an example of using an object that extends java.util.Iterator:

public class LimitIterator implements Iterator, Iterable {
   private it
   private limit
   private count

   LimitIterator(Iterator it, int limit) {
      limit = limit;
      count = 0;
      it = it
   }

   boolean hasNext(){
      return (count >= limit) ? false : it.hasNext()
   }

   Object next() {
      if (!hasNext()) throw new java.util.NoSuchElementException()

      count++
      return it.next()
   }

   Iterator iterator(){
      return this;
   }

   void remove(){
      throw new UnsupportedOperationException("remove() not supported")
   }

}

// Create a range from 1 to 10000
// and an empty list.
def list = 1..10000
def shortList = []

// Ensure that everything is as expected
assert list instanceof java.util.List
assert list.iterator() instanceof java.util.Iterator
assert list.size() == 10000
assert shortList instanceof java.util.List

// Grab the first 100 elements out of the lists iterator object.
for (i in new LimitIterator(list.iterator(), 100)) {
    shortlist.add(i);
}
assert shortlist.size() == 100
+3
source

Groovy 1.8.1

list.take(100).collect { ... }

take 100 .

+17

You can use a range of indices to get the sublist and then apply collectto the sublist.

def result = list[0..100].collect { ... }
+3
source

All Articles