10 April 2010

Creating a map from its elements

Valid since: op4j 1.0

Description
Create a map given its keys and values as separate objects.

Scenario
We want to create a Map<String,String> peopleDept variable containing some people names as keys, and the departments they work for in our company as values:
// peopleDept == MAP [
//                   [ key="James Cheddar"; value="Finance" ]
//                   [ key="Richard Stilton"; value="Engineering" ]
//                   [ key="Bernard Brie"; value="Marketing" ]
//                   [ key="Antonio Cabrales"; value="Sales" ]
//                 ]

Recipe
We can just create a map operator by building the map on an entry-by-entry basis, and return it with get() before executing any other operation:

Map<String,String> peopleDept =
    Op.onMapFor("James Cheddar", "Finance").
            and("Richard Stilton", "Engineering").
            and("Bernard Brie", "Marketing").
            and("Antonio Cabrales", "Sales").get();

This looks good. But instead, as already mentioned in other recipes, because of the fact that this map holds keys and values of the same type (String), we could have created a list with all they keys and values in key, value, key, value, key, value... order and executed the couple() action to create the map:

Map<String,String> peopleDept =
    Op.onListFor(
        "James Cheddar",  "Finance",   "Richard Stilton",  "Engineering",
        "Bernard Brie",   "Marketing", "Antonio Cabrales", "Sales").
        couple().get();

Comments
The difference between these two methods is that the entry-by-entry map building method can be used always (whichever the key and value types), while the coupling method requires the resulting map to hold the same key and value types.

As an example, we could create a Map<String,Integer> peopleYearsInCo containing the relation between these persons and the number of years they have been working for the company:

Map<String,Integer> peopleYearsInCo =
    Op.onMapFor("James Cheddar", 12).
            and("Richard Stilton", 2).
            and("Bernard Brie", 7).
            and("Antonio Cabrales", 9).get();

No comments:

Post a Comment