Domanda

The take and drop methods were added to the list object in groovy v 1.8.1, and work like this:

def list = ['Simple', 'list', 'with', 5, 'items']   
assert list.take(2) == ['Simple', 'list']  

I only have v 1.8.0 available to me. How can I reimplement my own version of list.take(2) using Groovy v1.8.0 ?

Is it possible to do something like:

def list = ['Simple', 'list', 'with', 5, 'items']  
def limit = 2 
assert list['0..'+limit] == ['Simple', 'list']  

When I try this I get an exception.

È stato utile?

Soluzione

Slicing might accomplish the same goal:

def list = ['Simple', 'list', 'with', 5, 'items']   
assert list[0..1] == ['Simple', 'list']  

Altri suggerimenti

you could do it the way groovy does it

https://github.com/groovy/groovy-core/blob/master/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L6498

public static <T> List<T> take(List<T> self, int num) {
    if (self.isEmpty() || num <= 0) {
        return createSimilarList(self, 0);
    }
    if (self.size() <= num) {
        List<T> ret = createSimilarList(self, self.size());
        ret.addAll(self);
        return ret;
    }
    List<T> ret = createSimilarList(self, num);
    ret.addAll(self.subList(0, num));
    return ret;
}

the method createSimilarList can be found here

https://github.com/groovy/groovy-core/blob/master/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethodsSupport.java#L162

Along the same lines as GargantuChet's answer, you can slice it, but using an exclusive range:

List.metaClass.take { n ->
    def len = [n,delegate.size()].min()
    delegate[0..<len]
}

assert [1,2,3,4].take(2) == [1,2]
assert [1,2].take(2) == [1,2]
assert [1].take(2) == [1]
assert [].take(2) == []
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top