25 March 2010

Creating maps by zipping keys and values

Valid since: op4j 1.0

Description
Create a java.util.Map object by zipping keys and values. Zipping involves having an array, list or set of objects which we want to consider either keys or values for the new map, and then specify another sequence of objects (same number of them as the existing array, list or set) that will be paired one-to-one with the elements of the existing structure so that, either the original element is considered key and the new object is considered value (zip values), or the contrary (zip keys).

Scenario
We want to create a Map<String,Integer> of person names (keys) and ages (values). Specifically we want: {{"John"=27}, {"Mary"=49}, {"Derek"=19}}.

Recipe
We will zip the values (ages), so we will start by creating a list on the keys and then we will zip the corresponding ages:

Map<String,Integer> agesByName =
    Op.onListFor("John", "Mary", "Derek").zipValues(27, 49, 19).get();


Comments
We could have zipped the keys instead (althought it would have been less natural in this specific case):

Map<String,Integer> agesByName =
    Op.onListFor(27, 49, 19).zipKeys("John", "Mary", "Derek").get();

Remember that all maps created by op4j are ordered (java.util.LinkedHashMap), and thus the new map will keep the order of the original list when iterated.

Let's have a look at the equivalent Java code:
Map<String,Integer> agesByName= new LinkedHashMap<String,Integer>();
agesByName.put("John", 27);
agesByName.put("Mary", 49);
agesByName.put("Derek", 19);

No comments:

Post a Comment