Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy .collect with number of elements limit

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

For example if your source iterator was 1 million long and your limit was 100, you would end up with an array of 100 items.

like image 577
Matthew Kirkley Avatar asked Nov 21 '11 18:11

Matthew Kirkley


3 Answers

Since Groovy 1.8.1 you can also do

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

where take will return the first 100 elements from the list.

like image 110
Christoph Metzendorf Avatar answered Oct 30 '22 16:10

Christoph Metzendorf


If you are using any data structure that implements java.util.List you can do a collection.subList(0, 100) on it. Where 0 is the start index and 100 is the end. After that you'd pass the new collection into collect().

Here is an example 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
like image 29
icirellik Avatar answered Oct 30 '22 17:10

icirellik


You can use a range of indices to obtain a sublist, and then apply collect to the sublist.

def result = list[0..100].collect { ... }
like image 3
Antoine Avatar answered Oct 30 '22 15:10

Antoine