Search

Dark theme | Light theme

December 25, 2009

Groovy Goodness: Getting All Subsequences of a List

With Groovy 1.7 we can retrieve all subsequences from a collection with the subsequences() method. All possible subsequences of the elements in the list are returned.

def languages = ['Groovy', 'Clojure', 'Scala']

def sequences = languages.subsequences()

assert [['Clojure'], ['Scala'], ['Groovy']] == sequences.findAll { it.size() == 1 } as List
assert [['Clojure', 'Scala'], ['Groovy', 'Scala'], ['Groovy', 'Clojure']] == sequences.findAll { it.size() == 2 } as List
assert [['Groovy', 'Clojure', 'Scala']] == sequences.findAll { it.size() == 3}.toList()