Wiki

Clone wiki

bolts / CollectionsFunctional

Home * На русском

Functional Collection Operations

Simple collection operations are described on another page.

Primary functional collection operations are map and filter.

map

map — is an operation that transform collection by applying given function to each element. In bolts "map" operation is implemented in map method of CollectionF interface.

Example:

ListF<User> users = ...
ListF<String> userLogins = users.map(User.loginF());

This code snippet transforms list of users to list of user logins. loginF is described in Function page.

filter

filter takes collection and predicate, and returns new collection with elements that match predicate. Example:

ListF<User> users = ...
ListF<User> okUsers = users.filter(userLoginIsGoodF());

userLoginIsGoodF function may be implemeneted like this:

static Function1B<User> userLoginIsGoodF() {
  return User.loginF().andThen(StringUtils.emptyF()).notF();
}

More details on Function page.

flatMap

flatMap converts each element of collection to another collection and then concatenates resulting collections. Simple example:

Cf.list(Cf.list(1, 2), Cf.list(3)).flatMap(Function.<ListF<Integer>>identityF()) == Cf.list(1, 2, 3)

identityF — simple function that returns passed element. flatMap(identifityF()) actually does "flatten" operation.

reduce

reduceLeft operation reduces collection to single element.

Cf.list(1, 2, 5, 3).reduceLeft(Comparator.<Integer>naturalComparator().maxF()) == 5

finds max collection element. bolts CollectionFmax method is implemened using reduceLeft in AbstractCollectionF class.

Cf.list(1, 2, 4).reduceLeft(IntegerF.plusF()) == 7

sums collection elements.

Examples

There are several examples of functional collection operations in the source repositoty.

Updated