Rozszerzenia kolekcji Groovy
Poznaj rozbudowane możliwości kolekcji Java dostępne w Groovy, które upraszczają i uelastyczniają operowanie na danych.
Rozszerzenia kolekcji Groovy to bezpłatna lekcja Groovy & Gradle: JVM Automation and Build Engineering na CoddyKit. To lekcja 1 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Groovy & Gradle: JVM Automation and Build Engineering, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Groovy & Gradle: JVM Automation and Build Engineering zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
Groovy's Collection Power-Up
Groovy supercharges Java's standard collections (List, Map, Set) with many new, convenient methods. This makes your code shorter, more readable, and much more expressive.
You'll spend less time writing boilerplate and more time solving problems!
Easy List Initialization
Creating and populating lists in Groovy is a breeze. No need for new ArrayList<>() or repetitive add() calls. Just use square brackets []!
class Main {
static void main(String[] args) {
def numbers = [1, 2, 3, 4, 5]
def names = ["Alice", "Bob", "Charlie"]
println "Numbers: " + numbers
println "Names: " + names
}
}The Versatile `each` Method
The each method is your go-to for iterating over collections. It's concise and works with both Lists and Maps.
For lists, it's like a simplified loop. For maps, it iterates over entries.
class Main {
static void main(String[] args) {
def fruits = ["Apple", "Banana", "Cherry"]
fruits.each { fruit ->
println "I love " + fruit
}
}
}Transforming Lists with `collect`
The collect method creates a new list by transforming each element of the original list. It's perfect for mapping items to new values.
class Main {
static void main(String[] args) {
def numbers = [1, 2, 3]
def doubledNumbers = numbers.collect { it * 2 }
println "Original: " + numbers
println "Doubled: " + doubledNumbers
}
}Filtering Elements with `findAll`
Need to select elements that meet specific criteria? Use findAll. It returns a new list containing only the elements for which the closure evaluates to true.
class Main {
static void main(String[] args) {
def ages = [12, 18, 25, 7, 30]
def adults = ages.findAll { it >= 18 }
println "Ages: " + ages
println "Adults: " + adults
}
}Counting Matching Elements
The count method helps you quickly determine how many elements in a collection satisfy a given condition. It returns a single integer.
class Main {
static void main(String[] args) {
def scores = [85, 92, 78, 95, 88]
def highScores = scores.count { it > 90 }
println "Scores: " + scores
println "Number of high scores (>90): " + highScores
}
}Simplified Map Syntax
Groovy makes creating maps incredibly easy using square brackets [] and colons : for key-value pairs. Keys can often be unquoted strings.
class Main {
static void main(String[] args) {
def person = [name: "Anna", age: 30, city: "New York"]
println "Person: " + person
println "Name: " + person.name // Property-style access
println "Age: " + person["age"] // Map-style access
}
}Iterating Over Maps
Just like lists, maps can be iterated using each. The closure for maps typically takes two arguments: key and value.
You can also use eachWithIndex if you need the index.
class Main {
static void main(String[] args) {
def config = [mode: "dev", port: 8080]
config.each { key, value ->
println "${key}: ${value}"
}
}
}Accessing Properties with Spread `*.`
The spread operator *. is a powerful Groovy feature for collections. It applies a property access or method call to all elements in a collection, returning a new list of results.
class Person {
String name
int age
}
class Main {
static void main(String[] args) {
def people = [
new Person(name: "Alice", age: 25),
new Person(name: "Bob", age: 30)
]
def names = people*.name
println "People names: " + names
}
}Collection Challenge
Consider the following Groovy code snippet:
def items = [10, 25, 30, 45, 50]
def result = items.findAll { it > 20 }.collect { it / 5 }
println resultWhat will be the output of this code?
Recap: Groovy's Collection Power
You've explored how Groovy significantly enhances standard Java collections. We covered:
- Simplified List and Map creation.
- Powerful iteration with
each. - Transforming collections with
collect. - Filtering with
findAlland counting withcount. - The convenient Spread Operator
*.for bulk property access.
These features make working with data structures in Groovy much more efficient and enjoyable!
Często zadawane pytania
Czy lekcja „Rozszerzenia kolekcji Groovy” jest bezpłatna?
Tak — pełny tekst „Rozszerzenia kolekcji Groovy” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Groovy & Gradle: JVM Automation and Build Engineering, przejdź na CoddyKit PRO. Kurs Groovy & Gradle: JVM Automation and Build Engineering zawiera 4 lekcji w sumie.
Co nauczysz się w „Rozszerzenia kolekcji Groovy”?
Poznaj rozbudowane możliwości kolekcji Java dostępne w Groovy, które upraszczają i uelastyczniają operowanie na danych. Ćwiczysz Groovy & Gradle: JVM Automation and Build Engineering z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Groovy & Gradle: JVM Automation and Build Engineering?
Nie wymagamy żadnego doświadczenia. Groovy & Gradle: JVM Automation and Build Engineering w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 1 z 4.
Ile czasu zajmuje lekcja „Rozszerzenia kolekcji Groovy”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Groovy & Gradle: JVM Automation and Build Engineering?
Tak. Każda lekcja Groovy & Gradle: JVM Automation and Build Engineering zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Rozszerzenia kolekcji Groovy
- Zrozumienie domknięć Groovy
- Wzorce funkcyjne w Groovy
- Currying i komponowanie closures