Table of contents

  1. Data structure
    1. Manipulating lists
    2. Iterating on a list
  2. Map
  3. Combination and subsequence
  4. Spread operator (*)

Data structure

Manipulating lists

join: assert [1, 2, 3].join('-') == '1-2-3'
every: assert [1, 2, 3].every { it < 5 }
any: assert [1, 2, 3].any { it > 2 }
inject: Reduce operator

Iterating on a list

each: [1, 2, 3].each { println "Item: $it" }
eachWithIndex: ['a', 'b', 'c'].eachWithIndex { it, i -> println "$i: $it" }
findAll(=filter): assert [1, 2, 3].findAll { it > 1 } == [2, 3]
collect: 리스트 요소를 조작해서 새로운 list 로 만들 수 있다.

Map

Multivalue Map

def requestParam = new LinkedMultiValueMap<String, String>(
    [socialNo   : ['19xx0101'],
     name       : ['이승한'],
     gender     : ['M'],
     phoneNumber: ['01012341234']])

MergeMap

def mergedMap = [a:"foo"] + [b:"bar"]

Query string to Map in Groovy

def map = query.tokenize('&')*.tokenize('=').collectEntries()

Combination and subsequence

Groovy combination 과 subsequence 는 테스트 할 때 도움이 많이 된다. GroovyCollections:GroovyJavaDoc

  • subsequences: list.subsequences([1, 2, 3]) > [[1, 2, 3], [1, 3], [2, 3], [1, 2], [1], [2], [3]]
  • combinations
    • combinations([[1, 2], 'x']) > [[1, 'x'], [2, 'x']]
    • combinations([['a', 'b'],[1, 2, 3]]) is [['a', 1], ['b', 1], ['a', 2], ['b', 2], ['a', 3], ['b', 3]]

Spread operator (*)

list 를 Variable Argument 로 사용하는 방법 출처:StackOverflow

def to(String... emails) {
    emails.each { println "Sending email to: $it"}
}
def emails = ["t@a.com", "t@b.com", "t@c.com"]
to(*emails)