반응형
Groovy에서 조건부 수집을 작성하는 방법은 무엇입니까?
이 구조가 있다고 상상해보십시오.
class Foo {
String bar
}
지금은 여러 인스턴스가의 상상 Foo
그 bar
값 baz_1
, baz_2
및 zab_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
다음에 find
나 findAll
같은 다음을.
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
반응형
'IT TIP' 카테고리의 다른 글
프로그래밍 방식으로보기 너비 설정 (0) | 2020.11.26 |
---|---|
Mongoose JS를 통한 MongoDB-findByID 란 무엇입니까? (0) | 2020.11.26 |
powershell을 사용하여 레지스트리 키의 값과 값만 가져 오는 방법 (0) | 2020.11.26 |
jQuery AJAX 호출에서 '최종'과 유사한 것이 있습니까? (0) | 2020.11.26 |
입력 텍스트 요소에 대한 올바른 읽기 전용 속성 구문은 무엇입니까? (0) | 2020.11.26 |