Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Kenneth A. Kousen - Making Java Groovy - 2014.pdf
Скачиваний:
50
Добавлен:
19.03.2016
Размер:
15.36 Mб
Скачать

Collections

307

One of the nicest features of Groovy collections is that they’re searchable. Groovy adds both find and findAll methods to collections. The find method takes a closure and returns the first element that satisfies the closure:

assert 'New Hampshire' ==

['New Hampshire','New Jersey','New York'].find { it =~ /New/ }

The findAll method returns all the elements that satisfy the closure. This example returns all the cities that have the letter e in their name:

def withE = cities.findAll { city -> city =~ /e/ } assert withE == ['Seattle', 'New York', 'Cleveland']

Groovy also supplies the methods any and every, which also take closures:

assert cities.any { it.size() < 7 } assert cities.every { it.size() < 10 }

The first expression states that there’s at least one city whose name is less than 7 characters. The second expression says that all of the city names are 10 characters or less.

Table B.1 summarizes the searchable methods.

Table B.1 Searchable methods added to Groovy collections

Method

Description

 

 

any

Returns true if any element satisfies closure

every

Returns true if all elements satisfy closure

find

Returns first element satisfying closure

findAll

Returns list of all elements satisfying closure

 

 

Finally, the join method concatenates all the elements of the list into a single string, using the supplied separator:

assert cities.join(',') == "Boston,Seattle,New York,Cleveland"

The combination of native syntax and added convenience methods makes Groovy lists much easier to work with than their Java counterparts. As it turns out, maps are improved the same way.

B.4.3 Maps

Groovy maps are like Java maps, but again with a native syntax and additional helper methods. Groovy uses the same square-bracket syntax for maps as for lists, but each entry in the map uses a colon to separate the key from its corresponding value.

You can populate a map right away by adding the elements when you declare the map itself:

www.it-ebooks.info

308

APPENDIX B Groovy by feature

def trivialMap = [x:1, y:2, z:3] assert 1 == trivialMap['x']

assert trivialMap instanceof java.util.HashMap

This defines a map with three entries. When adding elements to the map, the keys are assumed to be strings, so you don’t need to put quotes around them. The values can be anything.

MAP KEYS When adding to a map, the keys are assumed to be of type string, so no quotes are necessary.

You can add to a map using either Java or Groovy syntax:

def ALEast10 = [:] ALEast.put('Boston','Red Sox')

assert 'Red Sox' == ALEast.get('Boston') assert ALEast == [Boston:'Red Sox'] ALEast['New York'] = 'Yankees'

Accessing values can be done with either the array-like syntax shown, or using a dot. If the key has spaces in it, wrap the key in quotes:

assert 'Red Sox' == ALEast.Boston assert 'Yankees' == ALEast.'New York'

I’ve been using def to define the map reference, but Groovy understands Java generics:

Map<String,String> ALCentral = [Cleveland:'Indians', Chicago:'White Sox',Detroit:'Tigers']

assert 3 == ALCentral.size()

assert ALCentral.Cleveland == 'Indians'

Maps have a size method that returns the number of entries. Actually, the size method is universal.

SIZE In Groovy, the size method works for arrays, lists, maps, strings, and more.

Maps have an overloaded plus operation that combines the entries from two maps:

def both = ALEast + ALCentral assert 5 == both.size()

Like Java maps, you can extract the set of keys from a map using the keySet method:

assert ALEast.keySet() == ['Boston','New York'] as Set

Maps also have a rather controversial method that lets you add a new element with a default in case the element doesn’t exist:

assert 'Blue Jays' == ALEast.get('Toronto','Blue Jays') assert 'Blue Jays' == ALEast['Toronto']

Here I’m trying to retrieve a value using a key that isn’t in the map (Toronto). If the key exists, its value is returned. If not, it’s added to the map, with the second argument

10 For non-baseball people, ALEast is short for the Eastern division of the American League.

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]