IT TIP

Groovy에서 조건부 수집을 작성하는 방법은 무엇입니까?

itqueen 2020. 11. 26. 20:36
반응형

Groovy에서 조건부 수집을 작성하는 방법은 무엇입니까?


이 구조가 있다고 상상해보십시오.

class Foo {
   String bar
}

지금은 여러 인스턴스가의 상상 Foobarbaz_1, baz_2zab_3.

bar텍스트를 포함하는 값만 수집하는 collect 문을 작성하고 싶습니다 baz. 나는 그것을 작동시킬 수 없지만 다음과 같이 보일 것입니다.

def barsOfAllFoos = Foo.getAll().bar
assert barsOfAllFoos == [ 'baz_1', 'baz_2', 'zab_3' ]
def barsWithBaz = barsOfAllFoos.collect{ if( it.contains( "baz" ) { it } ) } // What is the correct syntax for this?
assert barsWithBaz == [ 'baz_1', 'baz_2' ]

다음이 필요합니다 findAll.

barsOfAllFoos.findAll { it.contains 'baz' }

필터링과 변환을 모두 수행하려면 여러 가지 방법이 있습니다. 1.8.1 이후 #findResults에는 건너 뛰려는 요소에 대해 null을 반환하는 클로저를 사용합니다.

def frob(final it) { "frobbed $it" }

final barsWithBaz = barsOfAllFoos.findResults {
    it.contains('baz')? frob(it) : null
}

이전 버전에서는 #findAll#collect

final barsWithBaz = barsOfAllFoos
                  . findAll { it.contains('baz') }
                  . collect { frob(it) }

또는 #sum

final barsWithBaz = barsOfAllFoos.sum([]) {
    it.contains('baz')? [frob(it)] : []
}

또는 #inject

final barsWithBaz = barsOfAllFoos.inject([]) {
    l, it -> it.contains('baz')? l << frob(it) : l
}

사용 findResults하면 (예를 들어 많은 라인의 정규식 검색) 상태 사용할 수있는 일치하는 값의 변환 된 버전 수집 할 경우 ... 나를 위해 일을하지 않았다 collect다음에 findfindAll같은 다음을.

def html = """
    <p>this is some example data</p>
    <script type='text/javascript'>
        form.action = 'http://www.example.com/'
        // ...
    </script>
"""

println("Getting url from html...")
// Extract the url needed to upload the form
def url = html.split("\n").collect{line->
    def m = line =~/.*form\.action = '(.+)'.*/
    if (m.matches()) {
        println "Match found!"
        return m[0][1]
    }
}.find()

println "url = '${url}'"

이것은 주어진 패턴과 일치하는 라인 부분을 반환합니다.

Getting url from html...
Match found!
url = 'http://www.example.com/'

참고 URL : https://stackoverflow.com/questions/12866664/how-to-write-a-conditional-collect-in-groovy

반응형