본문 바로가기

Script/Groovy

09. Collection

Groovy 의 Collection 은 JAVA 의 Collection 보다 사용이 상당히 편하다.
 
 
 
Range
 
이론 부분은  http://groovy-lang.org/api.html 에서 Range 로 검색해보면
 
해당 클래스는 인터페이스로 사용자 입력에 따라 IntRange 등으로 변형된다.
 
사용자의 Range 입력은 From .. To 형식으로 입력하면 되며 부등호를 사용할 수 있다.
 
선언한 
Range r = 1..10
println r
println r.class
println r.from
println r.to
1..10
class groovy.lang.IntRange
1
10
Range r2 = 1..<10
println r2.from
println r2.to
1
9
def today = new Date()
def onWeekAway = today + 7
 
for (def day : today..onWeekAway) {
println day
}
Mon Oct 14 13:18:46 KST 2019
Tue Oct 15 13:18:46 KST 2019
Wed Oct 16 13:18:46 KST 2019
Thu Oct 17 13:18:46 KST 2019
Fri Oct 18 13:18:46 KST 2019
Sat Oct 19 13:18:46 KST 2019
Sun Oct 20 13:18:46 KST 2019
Mon Oct 21 13:18:46 KST 2019
 
 
Lists
 
 
Java 에 비해 Groovy 의 Lists 선언은 상당히 편리하다.
 
단순히 [ lists ] 형식으로 넣으면 되기 때문이다.
 
def nums = [1,2,3,4,5]
println nums
println nums.class
[1, 2, 3, 4, 5]
class java.util.ArrayList
 
Add 는 다음과 같이 메소드와 오퍼레이터를 사용해서 넣을 수 있는데 
 
메서드를 사용하는 것보다 [ ] 오퍼레이터를 통해 리스트 값을 대체하거나 
 
+ 오퍼레이터를 통해서 데이터를 더 push 할 수 있다.
 
사용상 메서드는 현재 리스트를 바로 수정하고 오퍼레이터는 = 으로 변경된 
 
데이터를 다른 리스트로 옮기는 방식으로 사용한다. 
 
def nums = [1,2,3,4,5]
println nums
 
//replace
nums[1] = 10
println nums
 
//add
nums = nums + 7
println nums
 
nums = nums + [10,11,12]
println nums
[1, 2, 3, 4, 5]
[1, 10, 3, 4, 5]
[1, 10, 3, 4, 5, 7]
[1, 10, 3, 4, 5, 7, 10, 11, 12]
 
Remove 방식도 크게 다르지 않고 메서드와 - 오퍼레이터를 활용하면 된다.
 
def nums = [10,11,12,13,14]
println nums
 
//pop
nums.pop()
println nums
 
//remove Index
nums.removeAt(1)
println nums
 
//remove Item matched
def newNums = nums - 11
println newNums
[10, 11, 12, 13, 14]
[11, 12, 13, 14]
[11, 13, 14]
[13, 14]
 
이밖에도 << 오퍼레이터는 어레이에 어레이를 넣을 때 사용하며 
 
unique 메서드를 사용하면 중복 데이터를 제거할 수 있다.
 
 
 
Maps
 
Key, Value 페어로 이뤄진 Map 컬렉션 데이터 타입을 살펴보자.
 
기본적으로 Java 의 Map 과 같지만 사용법은 훨씬 쉽다.
 
def map = [:]
println map.getClass().getName()
 
def person = [first:"Daeung",last:"Kim",email:"kin3303@gmail.com"]
 
println person
println person.first
 
java.util.LinkedHashMap
 
[first:Daeung, last:Kim, email:kin3303@gmail.com]
 
Daeung
 
키 페어를 추가하는 경우는 = 오퍼레이터를 통해서 간단히 추가할 수 있다.
 
def person = [first:"Daeung",last:"Kim",email:"kin3303@gmail.com"]
 
person.twitter = "@twitter"
 
for(entry in person) {
println entry
}
 
for(key in person.keySet()) {
println key
}
 
for(key in person.keySet()) {
println "${key} : ${person[key]}"
}
first=Daeung
last=Kim
twitter=@twitter
 
first
last
email
twitter
 
first : Daeung
last : Kim
twitter : @twitter
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

'Script > Groovy' 카테고리의 다른 글

11. Conditional Statement  (0) 2020.01.21
10. Closures  (0) 2020.01.21
08. RegExp  (0) 2020.01.21
07. String  (0) 2020.01.21
06. Operator Overloading  (0) 2020.01.21